MongoDB query to display all the fields value, except _id

MongoDBDatabaseBig Data Analytics

Let us create a collection with documents −

> db.demo590.insert([
...    { "Name": "Chris", "Age": 21 },
...    {"Name": "Bob", "Age": 20},
...    { "Name": "Sam", "Age": 19 }
... ]);
BulkWriteResult({
   "writeErrors" : [ ],
   "writeConcernErrors" : [ ],
   "nInserted" : 3,
   "nUpserted" : 0,
   "nMatched" : 0,
   "nModified" : 0,
   "nRemoved" : 0,
   "upserted" : [ ]
})

Display all documents from a collection with the help of find() method −

> db.demo590.find();

This will produce the following output −

{ "_id" : ObjectId("5e92d514fd2d90c177b5bcd0"), "Name" : "Chris", "Age" : 21 }
{ "_id" : ObjectId("5e92d514fd2d90c177b5bcd1"), "Name" : "Bob", "Age" : 20 }
{ "_id" : ObjectId("5e92d514fd2d90c177b5bcd2"), "Name" : "Sam", "Age" : 19 }

Following is the query to display all the fields value, except _id −

> var listOfObject = [];
> db.demo590.find().forEach(function(d){
...    var ob = {};
...    ob["StudentFirstName"] = d.Name;
...    ob["StudentAge"] = d.Age;
...    listOfObject.push(ob);
... });

Following is the query to display the documents −

> listOfObject;

This will produce the following output −

[
   {
      "StudentFirstName" : "Chris",
      "StudentAge" : 21
   },
   {
      "StudentFirstName" : "Bob",
      "StudentAge" : 20
   },
   {
      "StudentFirstName" : "Sam",
      "StudentAge" : 19
   }
]
raja
Published on 15-May-2020 06:49:54
Advertisements