MongoDB Installation and Basic commands

Source: Internet
Author: User
Tags findone prev


Installing MongoDB (MONGODB-LINUX-X86_64-3.2.4.TGZ)
1 export path= $PATH:/usr/local/mongodb/bin
2/usr/local/mongodb/bin New mongodb.conf
port=27017
dbpath=/opt/mongodb/data/db
Logpath=/opt/mongodb/logs/mongodb.log
Logappend=true
Fork=true
3./mongod-f mongodb.conf Server Start-up
./mongod-f mongodb.conf--rest

4 Stop
Use admin
Db.shutdownserver ();

Using "Spring 3.1.2.RELEASE version" + "Spring-data-mongodb 1.3.0.RELEASE" + "Mongo-java-driver 2.11.1"

Show DBS;
Db.logfile.stats ();
Db.collection.stats ();
Db.logfiledb.stats ();
Db.collection.find ()
Db.collection.findOne ()
Db.getcollection ("Foo-ee") Get Foo-ee Collection

Db.collection.remove ()//Both the collection itself and the index are preserved
Db.drop_collection ("collection")//entire set and index are deleted
Db.tbname.drop ()

db.update{criterial,{"$inc": {"pageviews": 1}}}//value plus 1
db.update{criterial,{"$set": {"key": "Val"}}}//value modified
db.update{criterial,{"$push": {"key": "Val"}}}//array push

db.update{{"key": {"$ne": "Temp"}},{"$push": {"key": "Temp"}}}//If TEMP does not exist in the array, insert
db.update{criterial,{"$addToSet": {"key": "Temp"}}}//Can be inserted to avoid duplication
db.update{criterial,{"$addToSet": {"key": {"$each": ["Val1", "Val1", "Val1"]}}}}//addtoset and each combination
Db.update ({},{"$pull": {"key": "Val1"}})//erase all matching parts
Db.update ({"Comments.author": "Jhone"},{"$set": {"Comments.$.author": "Jim"}})//Replace the qualifying name in the array with a locator
Db.update ({"Count": 25},{"$inc": {"Count": 3}},true)//The third parameter true means that Upsert does not match, adds a 25, and then increases to 28

Db.find (criterial,{"Key1": 1, "Key2": 0})//Return value contains Key1, not including Key2

Start=new Date ("2015-01-01")
Db.find ({"Stat_date", {"$lt": Start}}//LT GT LTE GTE date accurate to milliseconds
Db.find ({"key": {"$ne": "Val"}}//key!=val

Db.find ({"$or": [{"Key1": {"$in": [123, "456"]}},{"Key2": "Val2"}]})//$in several different types of values $nin $or
Db.find ({"key": {"$not": {"$mod": [5,1]}})//$mod Take the value of the remainder%5=1 $not

Db.find ({"key": {"$in": [null], "$exists": True}})//key exists and the value is null
Db.find ({"key": null})//The value is null or the document does not exist for the key
Db.find ({"Key":/val/i})//Regular

Array
Db.food.insert ({"Fruit": ["apple", "banana", "Peach"]})
Db.food.find ({"Fruit": "apple"})
Db.food.find ({"Fruit": {"$all": ["apple", "Banana"]}})//contains both
Db.food.find ({"fruit.2": "Banana"})

Db.food.find ({"Fruit": {"$size": 3}})//can only be used to find fixed-length arrays and cannot use range queries
Db.food.update ({"$push": {"fruit": "Strawberry"}, "$inc": {"size": 1}})
Db.food.find ({"size": {"$GT": 3}})//increase size to implement range query

Db.log.findOne (criterial,{"comments": {"$slice":-10}})//return array after 10 and document all fields
Db.log.findOne (criterial,{"comments": {"$slice": 10}})//Returns the first 10 of the array and all the fields of the document
Db.log.findOne (criterial,{"comments": {"$slice": [25,10]}})//returns the 25th element of the array to 35 and all fields of the document

Db.log.find ({"name": {"First": "Je", "last": "FA"}})//fixed order lookup, exact match
Db.log.find ({"Name.first": "Je," name.last ":" FA "})//no fixed order
Db.log.find ({"Comments": {"Name.first": "Je," name.last ":" FA "}})//comments save the array, as long as the comments contains more than two values in the embedded document. With one of the following differences
Db.log.find ({"Comments": {"$elemMatch": {"Name.first": "Je," name.last ":" Fa "}}})//comments save array, ELEMMATCH specifies an array of single inline document qualifications

Where cannot use index
Db.log.find ({"$where": "this.x+this.y==10"})
Db.log.find ({"$where": "function () {return this.x+this.y==10;}"})

Db.stock.find ({"desc": "MP3"}). Limit ((). Skip ({uname:1,age:-1})//skip too much impact performance, sort 1 ascending-1 Descending paging lookup

Index
Db.log.ensureIndex ({"Date": 1, "uname": 1},{"name": "Date_1_uname_1"})//index name
Db.log.ensureIndex ({"Date": 1},{"unique": true},{"Background": true})//index name background processing can prevent blocking requests when indexing
Db.stock.find ({"desc": "MP3"}). Hint ({"desc": 1})

Geo-spatial indexes are assumed to be on a flat surface
Find near point documents by fine latitude
{"GPs": {"x": -30, "Y": 30}}
Db.map.ensureIndex ({"GPs": "2d"},{"min": -1000, "Max": 1000})
Db.map.find ({"GPs": {"$near": [40,-73]}}). Limit (10)
Db.runcommand ({geonear: "Map", near:[40,-73],num:10})
Find a coffee shop by fine latitude
Db.map.ensureIndex ({"GPs": "2d", "desc": 1})
Db.map.find ({"GPs": {"$near": [40,-73]}, "desc": "Coffee"}). Limit (1)

Db.log.count ()
Db.log.count ({"X": 1})

[{"Day": "2010-10-03", "Time": "2010-10-03 03:55:22", price:3},{"Day": "2010-10-03", "Time": "2010-10-03 04:55:22", Price:3},{"Day": "2010-10-03", "Time": "2010-10-03 05:55:22", Price:3}]
Db.runcommand ({"Distinct", "tbname", "Key": "UserID"})
Db.runcommand ({"group": {
"NS": "GP",//Set name
"Key": {"Day": true},//Group field
"Initial": {"Time": 0},
"$reduce": function (doc,prev) {//max
if (doc.time>prev.time) {
Prev.price=doc.price;
Prev.time=doc.time;
}
},
"$finalize": function (prev) {//Change return result
if (prev.price=3) {
Delete Prev.price
}
}
}
})
MongoDB stipulates that the group cannot record more than 10,000 records at a time, more than 10,000 must be calculated with map reduce

Map reduce
Map=function () {
for (var key in this) {
Emit (Key,{count:1});
}
}
Reduce=function (key,emits) {
total=0;
for (var i in emits) {
Total+=emits[i].count;
}
return {"Count": total};
}
Mr=db.runcommand ({"MapReduce": "Tbname", "map": Map, "Reduce": reduce})
Db[mr.result].find ()

Db.listcommands ()

Fixed collection, you can use a trailing cursor in your program to get the newly added document
Db.createcollection ("collection", {capped:true,size:10000,max:100})//Create fixed set, big trifle 10000 bytes
Db.createcollection ("Mycappedcoll", {capped:true,size:10000,max:100,autoindexid:false})
Db.my_collection.find (). Sort ({"$natural":-1})//query in order of insertion is also natural order,-1 is reverse

Create user
Db.createrole (
{
Role: "Root",
Privileges: [
{resource: {db: "LogFile", Collection: ""}, Actions: ["Find", "Update", "Insert", "Remove"]}
],
Roles: []
}
)
Db.createuser (
{
User: "Root",
PWD: "pwd",
roles: [Root]//root default Super Admin
}
)
Db.createuser ({
User: "LogFile",
PWD: "pwd",
Roles: [{role: ' Root ', DB: ' LogFile '}]
});

Db.getusers ()
Db.grantrolestouser ("root", [{role: "root", DB: "LogFile"}])
Db.auth ("root", "jscnbi_123654")

MongoDB Installation and Basic commands

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.