Collections

MongoDB collections

Published: Thursday, 2 July 2015
mongodb

A collection holds many documents. A document can be considered a JSON object, which may have nested fields.

List all collections in a db

> use exampledb
switched to db exampledb
> show collections
animal
system.indexes

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

> 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

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

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

Show indexes on a collection

> db.animal.getIndexes()
[
    {
        "v" : 1,
        "key" : {
            "_id" : 1
        },
        "ns" : "exampledb.animal",
        "name" : "_id_"
    }
]