文章目录
  1. 1. Getting-started
  2. 2. Generate Test Data
  3. 3. MongoDB CRUD
  4. 4. MongoDB Limits and Thresholds
  5. 5. MongoDB Drivers and Client Libraries

MongoDB初读

Getting-started

getting-started

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
show dbs

use mydb

db

help

j = { name : "mongo" }
k = { x : 3 }
db.testData.insert( j )
db.testData.insert( k )

show collections

db.testData.find()

var c = db.testData.find()
while ( c.hasNext() ) printjson( c.next() )

var c = db.testData.find()
printjson( c [ 1 ] )

db.testData.find( { x : 3 } )

db.testData.findOne()

db.testData.find().limit(3)

Generate Test Data

1
2
3
for (var i = 1; i <= 25; i++) db.testData.insert( { x : i } )

db.testData.find()

MongoDB CRUD

BSON

MongoDB query operation MongoDB query operation the same query in SQL the same query in SQL

Projections

"_id": 0, "name": 1 , "email": 1 => select name, email

Query Behavior

MongoDB queries exhibit the following behavior:

All queries in MongoDB address a single collection. You can modify the query to impose limits, skips, and sort orders. The order of documents returned by a query is not defined unless you specify a sort(). Operations that modify existing documents (i.e. updates) use the same query syntax as queries to select documents to update. In aggregation pipeline, the $match pipeline stage provides access to MongoDB queries. MongoDB provides a db.collection.findOne() method as a special case of find() that returns a single document.

Cursor Information

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
You can use the command cursorInfo to retrieve the following information on cursors:

total number of open cursors
size of the client cursors in current use
number of timed out cursors since the last server restart
Consider the following example:

db.runCommand( { cursorInfo: 1 } )
The result from the command returns the following document:

{
  "totalOpen" : <number>,
  "clientCursors_size" : <number>,
  "timedOut" : <number>,
  "ok" : 1
}

Analyze Query Performance To use the explain() method, call the method on a cursor returned by find().

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
db.inventory.find( { type: 'food' } ).explain()

{
  "cursor" : "BtreeCursor type_1",
  "isMultiKey" : false,
  "n" : 5,
  "nscannedObjects" : 5,
  "nscanned" : 5,
  "nscannedObjectsAllPlans" : 5,
  "nscannedAllPlans" : 5,
  "scanAndOrder" : false,
  "indexOnly" : false,
  "nYields" : 0,
  "nChunkSkips" : 0,
  "millis" : 0,
  "indexBounds" : { "type" : [
                                [ "food",
                                  "food" ]
                             ] },
  "server" : "mongodbo0.example.net:27017" }

With an upsert, applications can decide between performing an update or an insert operation using just a single call. Both the update() method and the save() method can perform an upsert. See update() and save() for details on performing an upsert with these methods.

SQL to MongoDB Mapping Chart for additional examples of MongoDB write operations and the corresponding SQL statements. !!!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
db.inventory.insert( { _id: 10, type: "misc", item: "card", qty: 15 } )
db.inventory.update(
                     { type: "book", item : "journal" },
                     { $set : { qty: 10 } },
                     { upsert : true }
                   )
db.inventory.save( { type: "book", item: "notebook", qty: 40 } )



db.inventory.find( { type: "snacks" } )
db.inventory.find( { type: { $in: [ 'food', 'snacks' ] } } )
db.inventory.find( { type: 'food', price: { $lt: 9.95 } } )
db.inventory.find(
                   { $or: [
                            { qty: { $gt: 100 } },
                            { price: { $lt: 9.95 } }
                          ]
                   }
                 )

Specify AND as well as OR Conditions

With additional clauses, you can specify precise conditions for matching documents.

In the following example, the compound query document selects all documents in the collection where the value of the type field is 'food' and either the qty has a value greater than ($gt) 100 or the value of the price field is less than ($lt) 9.95:

1
2
3
db.inventory.find( { type: 'food', $or: [ { qty: { $gt: 100 } },
                                            { price: { $lt: 9.95 } } ]
                   } )

Details http://docs.mongodb.org/manual/tutorial/query-documents/

Remove Documents

Remove All Documents The following example removes all documents from the inventory collection: db.inventory.remove()

Remove Documents that Matches a Condition db.inventory.remove( { type : "food" } )

Remove a Single Document that Matches a Condition To remove a single document, call the remove() method with the justOne parameter set to true or 1. db.inventory.remove( { type : "food" }, 1 )

Query Cursor Methods

1
2
3
4
5
6
7
8
9
Name  Description
cursor.count()  Returns a count of the documents in a cursor.
cursor.explain()  Reports on the query execution plan, including index use, for a cursor.
cursor.hint() Forces MongoDB to use a specific index for a query.
cursor.limit()  Constrains the size of a cursor’s result set.
cursor.next() Returns the next document in a cursor.
cursor.skip() Returns a cursor that begins returning results only after passing or skipping a number of documents.
cursor.sort() Returns results ordered according to a sort specification.
cursor.toArray()  Returns an array that contains all documents returned by the cursor.

Query and Data Manipulation Collection Methods

1
2
3
4
5
6
7
8
9
Name  Description
db.collection.count() Wraps count to return a count of the number of documents in a collection or matching a query.
db.collection.distinct()  Returns an array of documents that have distinct values for the specified field.
db.collection.find()  Performs a query on a collection and returns a cursor object.
db.collection.findOne() Performs a query and returns a single document.
db.collection.insert()  Creates a new document in a collection.
db.collection.remove()  Deletes documents from a collection.
db.collection.save()  Provides a wrapper around an insert() and update() to insert new documents.
db.collection.update()  Modifies a document in a collection.

DBrefs

个人觉得:MongoDB 是以key-value模式进行存储的,所以是不建议复杂关联关系的。
Mongodb联合查询
MongoDB的多表关联操作

ObjectId

ObjectId is a 12-byte BSON type, constructed using:

1
2
3
4
a 4-byte value representing the seconds since the Unix epoch,
a 3-byte machine identifier,
a 2-byte process id, and
a 3-byte counter, starting with a random value.

ObjectId 是一个很有意思的东东,

> ObjectId("507c7f79bcf86cd7994f6c0e").getTimestamp()
ISODate("2012-10-15T21:26:17Z")
  • 1 in the mongo shell, you can access the creation time of the ObjectId, using the getTimestamp() method.
  • 2 sorting on an _id field that stores ObjectId values is roughly equivalent to sorting by creation time.

Enable Authentication

Security > Security Tutorials > Access Control Tutorials > Enable Authentication

MongoDB Limits and Thresholds

MongoDB Limits and Thresholds

MongoDB Drivers and Client Libraries

MongoDB Drivers and Client Libraries

突然发现还有个Mongo training
使用MMS(MongoDB Monitoring Service)监控MongoDB

文章目录
  1. 1. Getting-started
  2. 2. Generate Test Data
  3. 3. MongoDB CRUD
  4. 4. MongoDB Limits and Thresholds
  5. 5. MongoDB Drivers and Client Libraries