MongoDB
Kim 2015.05.01
Document
{
"_id": "10280",
"city": "NEW YORK",
"state": "NY",
"pop": 5574,
"loc": [-74.016323, 40.710537]
}
Query Documents
db.collection.find(query, projection)
Query Documents
Select All Documents in a Collection
db.inventory.find( {} )
db.inventory.find()
Query Documents
Specify Equality Condition
To specify equality condition, use the query document { <field>: <value> } to select all documents that contain the
<field> with the specified <value>.
db.inventory.find( { type: "snacks" } )
Query Documents
Specify Conditions Using Query Operators
The following example selects all documents in the inventory collection where the value of the typefield is either
'food' or 'snacks'
db.inventory.find( { type: { $in: [ 'food', 'snacks' ] } } )
Although you can express this query using the $or operator, use the $in operator rather than the $oroperator when
performing equality checks on the same field.
Query Documents
Specify AND Conditions
db.inventory.find( { type: 'food', price: { $lt: 9.95 } } )
This query selects all documents where the type field has the value 'food' and the value of the pricefield is less than
9.95. See comparison operators for other comparison operators.
Query Documents
Specify OR Conditions
db.inventory.find(
{
$or: [ { qty: { $gt: 100 } }, { price: { $lt: 9.95 } } ]
}
)
Query Documents
Embedded Documents
In the following example, the query matches all documents where the value of the field producer is an embedded
document that contains only the field company with the value 'ABC123' and the field address with the value '123
Street', in the exact order:
db.inventory.find({
producer: {
company: 'ABC123',
address: '123 Street'
}
})
Query Documents
Equality Match on Fields within an Embedded Document
In the following example, the query uses the dot notation to match all documents where the value of the field producer
is an embedded document that contains a field company with the value 'ABC123' and may contain other fields:
db.inventory.find( { 'producer.company': 'ABC123' } )
Query Documents
{ _id: 5, type: "food", item: "aaa", ratings: [ 5, 8, 9 ] }
{ _id: 6, type: "food", item: "bbb", ratings: [ 5, 9 ] }
{ _id: 7, type: "food", item: "ccc", ratings: [ 9, 5, 8 ] }
The following example queries for all documents where the field ratings is an array that holds exactly three elements,
5, 8, and 9, in this order:
db.inventory.find( { ratings: [ 5, 8, 9 ] } )
The operation returns the following document:
{ "_id" : 5, "type" : "food", "item" : "aaa", "ratings" : [ 5, 8, 9 ] }
Query Documents
Match an Array Element
db.inventory.find( { ratings: 5 } )
The operation returns the following documents:
{ "_id" : 5, "type" : "food", "item" : "aaa", "ratings" : [ 5, 8, 9 ] }
{ "_id" : 6, "type" : "food", "item" : "bbb", "ratings" : [ 5, 9 ] }
{ "_id" : 7, "type" : "food", "item" : "ccc", "ratings" : [ 9, 5, 8 ] }
Query Documents
Match a Specific Element of an Array
In the following example, the query uses the dot notation to match all documents where the ratings array contains 5 as
the first element:
db.inventory.find( { 'ratings.0': 5 } )
The operation returns the following documents:
{ "_id" : 5, "type" : "food", "item" : "aaa", "ratings" : [ 5, 8, 9 ] }
{ "_id" : 6, "type" : "food", "item" : "bbb", "ratings" : [ 5, 9 ] }
Insert Documents
db.inventory.insert(
{
item: "ABC1",
details: {
model: "14Q3",
manufacturer: "XYZ Company"
},
stock: [ { size: "S", qty: 25 }, { size: "M", qty: 50 } ],
category: "clothing"
}
)
Insert Documents
var mydocuments =
[
{
item: "ABC2",
details: { model: "14Q3", manufacturer: "M1 Corporation" }
},
{
item: "MNO2",
stock: [ { size: "S", qty: 5 }, { size: "M", qty: 5 }, { size: "L", qty: 1 } ]
},
];
db.inventory.insert( mydocuments );
Insert Documents
Insert Multiple Documents with Bulk
Initialize a Bulk operations builder for the collection inventory.
var bulk = db.inventory.initializeUnorderedBulkOp();
Insert Documents
bulk.insert(
{
item: "BE10",
details: { model: "14Q2", manufacturer: "XYZ Company" },
stock: [ { size: "L", qty: 5 } ],
}
);
bulk.insert(
{
item: "ZYT1",
details: { model: "14Q1", manufacturer: "ABC Company" },
stock: [ { size: "S", qty: 5 }, { size: "M", qty: 5 } ],
}
);
bulk.execute();
Modify Documents
db.collection.update(query, update, options)
db.collection.update(
<query>,
<update>,
{
upsert: <boolean>,
multi: <boolean>
}
)
Modify Documents
Update Specific Fields in a Document
db.inventory.update(
{ item: "MNO2" },
{
$set: {
category: "apparel",
details: { model: "14Q3", manufacturer: "XYZ Company" }
},
$currentDate: { lastModified: true }
}
)
Modify Documents
Update an embedded field
db.inventory.update(
{ item: "ABC1" },
{ $set: { "details.model": "14Q2" } }
)
Modify Documents
Update multiple documents
db.inventory.update(
{ category: "clothing" },
{
$set: { category: "apparel" },
$currentDate: { lastModified: true }
},
{ multi: true }
)
Modify Documents
Specify upsert: true for the update replacement operation
db.inventory.update(
{ item: "TBD1" },
{
item: "TBD1",
details: { "model" : "14Q4", "manufacturer" : "ABC Company" },
stock: [ { "size" : "S", "qty" : 25 } ],
category: "houseware"
},
{ upsert: true }
)
Modify Documents
Specify upsert: true for the update specific fields operation.
db.inventory.update(
{ item: "TBD2" },
{
$set: {
details: { "model" : "14Q3", "manufacturer" : "IJK Co." },
category: "houseware"
}
},
{ upsert: true }
)
Remove Documents
db.collection.remove(
<query>,
<justOne>
)
Remove Documents
The following example removes all documents from the inventory collection:
db.inventory.remove({})
Remove Documents
Remove Documents that Match a Condition
db.inventory.remove( { type : "food" } )
Iterate a Cursor in the mongo Shell
The db.collection.find() method returns a cursor. To access the documents, you need to iterate the cursor.
var myCursor = db.inventory.find( { type: 'food' } );
myCursor.forEach(printjson);
Iterate a Cursor in the mongo Shell
● cursor.count() Returns the total number of documents in a cursor.
● cursor.forEach() Applies a JavaScript function for every document in a cursor.
● cursor.hasNext() Returns true if the cursor has documents and can be iterated.
● cursor.limit() Constrains the size of a cursor’s result set.
● cursor.sort() Returns results ordered according to a sort specification.
● cursor.toArray() Returns an array that contains all documents returned by the cursor.

MongoDB

  • 1.
  • 2.
    Document { "_id": "10280", "city": "NEWYORK", "state": "NY", "pop": 5574, "loc": [-74.016323, 40.710537] }
  • 3.
  • 4.
    Query Documents Select AllDocuments in a Collection db.inventory.find( {} ) db.inventory.find()
  • 5.
    Query Documents Specify EqualityCondition To specify equality condition, use the query document { <field>: <value> } to select all documents that contain the <field> with the specified <value>. db.inventory.find( { type: "snacks" } )
  • 6.
    Query Documents Specify ConditionsUsing Query Operators The following example selects all documents in the inventory collection where the value of the typefield is either 'food' or 'snacks' db.inventory.find( { type: { $in: [ 'food', 'snacks' ] } } ) Although you can express this query using the $or operator, use the $in operator rather than the $oroperator when performing equality checks on the same field.
  • 7.
    Query Documents Specify ANDConditions db.inventory.find( { type: 'food', price: { $lt: 9.95 } } ) This query selects all documents where the type field has the value 'food' and the value of the pricefield is less than 9.95. See comparison operators for other comparison operators.
  • 8.
    Query Documents Specify ORConditions db.inventory.find( { $or: [ { qty: { $gt: 100 } }, { price: { $lt: 9.95 } } ] } )
  • 9.
    Query Documents Embedded Documents Inthe following example, the query matches all documents where the value of the field producer is an embedded document that contains only the field company with the value 'ABC123' and the field address with the value '123 Street', in the exact order: db.inventory.find({ producer: { company: 'ABC123', address: '123 Street' } })
  • 10.
    Query Documents Equality Matchon Fields within an Embedded Document In the following example, the query uses the dot notation to match all documents where the value of the field producer is an embedded document that contains a field company with the value 'ABC123' and may contain other fields: db.inventory.find( { 'producer.company': 'ABC123' } )
  • 11.
    Query Documents { _id:5, type: "food", item: "aaa", ratings: [ 5, 8, 9 ] } { _id: 6, type: "food", item: "bbb", ratings: [ 5, 9 ] } { _id: 7, type: "food", item: "ccc", ratings: [ 9, 5, 8 ] } The following example queries for all documents where the field ratings is an array that holds exactly three elements, 5, 8, and 9, in this order: db.inventory.find( { ratings: [ 5, 8, 9 ] } ) The operation returns the following document: { "_id" : 5, "type" : "food", "item" : "aaa", "ratings" : [ 5, 8, 9 ] }
  • 12.
    Query Documents Match anArray Element db.inventory.find( { ratings: 5 } ) The operation returns the following documents: { "_id" : 5, "type" : "food", "item" : "aaa", "ratings" : [ 5, 8, 9 ] } { "_id" : 6, "type" : "food", "item" : "bbb", "ratings" : [ 5, 9 ] } { "_id" : 7, "type" : "food", "item" : "ccc", "ratings" : [ 9, 5, 8 ] }
  • 13.
    Query Documents Match aSpecific Element of an Array In the following example, the query uses the dot notation to match all documents where the ratings array contains 5 as the first element: db.inventory.find( { 'ratings.0': 5 } ) The operation returns the following documents: { "_id" : 5, "type" : "food", "item" : "aaa", "ratings" : [ 5, 8, 9 ] } { "_id" : 6, "type" : "food", "item" : "bbb", "ratings" : [ 5, 9 ] }
  • 14.
    Insert Documents db.inventory.insert( { item: "ABC1", details:{ model: "14Q3", manufacturer: "XYZ Company" }, stock: [ { size: "S", qty: 25 }, { size: "M", qty: 50 } ], category: "clothing" } )
  • 15.
    Insert Documents var mydocuments= [ { item: "ABC2", details: { model: "14Q3", manufacturer: "M1 Corporation" } }, { item: "MNO2", stock: [ { size: "S", qty: 5 }, { size: "M", qty: 5 }, { size: "L", qty: 1 } ] }, ]; db.inventory.insert( mydocuments );
  • 16.
    Insert Documents Insert MultipleDocuments with Bulk Initialize a Bulk operations builder for the collection inventory. var bulk = db.inventory.initializeUnorderedBulkOp();
  • 17.
    Insert Documents bulk.insert( { item: "BE10", details:{ model: "14Q2", manufacturer: "XYZ Company" }, stock: [ { size: "L", qty: 5 } ], } ); bulk.insert( { item: "ZYT1", details: { model: "14Q1", manufacturer: "ABC Company" }, stock: [ { size: "S", qty: 5 }, { size: "M", qty: 5 } ], } ); bulk.execute();
  • 18.
    Modify Documents db.collection.update(query, update,options) db.collection.update( <query>, <update>, { upsert: <boolean>, multi: <boolean> } )
  • 19.
    Modify Documents Update SpecificFields in a Document db.inventory.update( { item: "MNO2" }, { $set: { category: "apparel", details: { model: "14Q3", manufacturer: "XYZ Company" } }, $currentDate: { lastModified: true } } )
  • 20.
    Modify Documents Update anembedded field db.inventory.update( { item: "ABC1" }, { $set: { "details.model": "14Q2" } } )
  • 21.
    Modify Documents Update multipledocuments db.inventory.update( { category: "clothing" }, { $set: { category: "apparel" }, $currentDate: { lastModified: true } }, { multi: true } )
  • 22.
    Modify Documents Specify upsert:true for the update replacement operation db.inventory.update( { item: "TBD1" }, { item: "TBD1", details: { "model" : "14Q4", "manufacturer" : "ABC Company" }, stock: [ { "size" : "S", "qty" : 25 } ], category: "houseware" }, { upsert: true } )
  • 23.
    Modify Documents Specify upsert:true for the update specific fields operation. db.inventory.update( { item: "TBD2" }, { $set: { details: { "model" : "14Q3", "manufacturer" : "IJK Co." }, category: "houseware" } }, { upsert: true } )
  • 24.
  • 25.
    Remove Documents The followingexample removes all documents from the inventory collection: db.inventory.remove({})
  • 26.
    Remove Documents Remove Documentsthat Match a Condition db.inventory.remove( { type : "food" } )
  • 27.
    Iterate a Cursorin the mongo Shell The db.collection.find() method returns a cursor. To access the documents, you need to iterate the cursor. var myCursor = db.inventory.find( { type: 'food' } ); myCursor.forEach(printjson);
  • 28.
    Iterate a Cursorin the mongo Shell ● cursor.count() Returns the total number of documents in a cursor. ● cursor.forEach() Applies a JavaScript function for every document in a cursor. ● cursor.hasNext() Returns true if the cursor has documents and can be iterated. ● cursor.limit() Constrains the size of a cursor’s result set. ● cursor.sort() Returns results ordered according to a sort specification. ● cursor.toArray() Returns an array that contains all documents returned by the cursor.