Thursday, October 15, 2020

Mongo DB - Working with Collections

Let us say we have a collection named 'Books' In the next few examples we will learn how to insert and select documents to and from this collection.

Use the following command to add/insert a document into a collection. Note that a column named "_id" will be automatically populated with a GUID (Global unique identifier) value every time a new document is inserted.

SYNTAX: db.<CollectionName>.insert(<DocumentInJsonFormat>);

EXAMPLE: db.Books.insert({title: "Learn MongoDB", author: "Anonymous", year: 2019});

You can use the following command to insert multiple documents at once. The box ('[' and ']') brackets are used to enclose multiple Json documents in an array of Json objects.

db.Books.insertMany([

  {title: "Learn MongoDB", author: "Anonymous", year: 2019},

  {title: "Learn NoSQL", author: "Anonymous", year: 2020}

]);

It is to be noted that there are two other variations of the insert command: insert() and insertOne(). insert() is similar to insertMany() - however, it has been deprecated in newer versions of Mongo engine. Whereas, the insertOne() command can be used similar to insertMany() - however, only for inserting a single document.

Following query returns all documents in the 'Books' collection.

db.Books.find({});

A more readable (well formatted Json) output can be obtained using the 'pretty()' function as shown below.

db.Books.find({}).pretty();

Use the following query to count the number of documents in a collection.

db.Books.find({})count();

The following query can be used to selectively display attributes from documents. The following query will return the columns: '_id', 'title' and 'author'. The 'year' attribute will not be returned. Specifying the value '1' after an attribute name will select that attribute. Similarly, specifying the value '0' or not specifying the attribute name altogether will suppress the attribute from appearing in the output result set.

db.Books.find({}, {title:1, author:1});

Notice above that by default the '_id' field is always displayed in the result set. You can suppress it by explicitly specifying '0' against it, as shown below.

db.Books.find({}, {_id:0, title:1, author:1});

Cheers.

No comments:

Post a Comment