Collections
A collection holds many documents. A document can be considered a JSON object, which may have nested fields.
List all collections in a db
Section titled “List all collections in a db”> use exampledbswitched to db exampledb> show collectionsanimalsystem.indexesInserting a document
Section titled “Inserting a document”To insert into the animal collection of the current database, run:
> db.animal.insert({name: "giraffe"})WriteResult({ "nInserted" : 1 })It will also create the collection if it does not exist.
List all documents in a collection
Section titled “List all documents in a collection”> db.animal.find(){ "_id" : ObjectId("5edcf84cd0be79d61935661a"), "name" : "giraffe" }The above shows documents in the animal collection of the current database.
List some documents in a collection
Section titled “List some documents in a collection”Finds all documents in the animal collection where name is equal to giraffe.
> db.animal.find({"name":"giraffe"}){ "_id" : ObjectId("5edcf84cd0be79d61935661a"), "name" : "giraffe" }Updating documents
Section titled “Updating documents”Removing a field from all documents in a collection
Section titled “Removing a field from all documents in a collection”> db.example_collection.update({}, {$unset: {unwanted_field:""} }, {multi: true})multi: true is required to update more than one matching document.
See the db.collection.update reference documentation.
Indexes
Section titled “Indexes”Show indexes on a collection
Section titled “Show indexes on a collection”> db.animal.getIndexes()[ { "v" : 1, "key" : { "_id" : 1 }, "ns" : "exampledb.animal", "name" : "_id_" }]