Create array with MongoDB query?

MongoDBDatabaseBig Data Analytics

You can use the concept of toArray() to create array. Following is the syntax −

db.yourCollectonName.find({}, {yourFieldName:1}).toArray();

Let us create a collection with documents −

> db.createArrayDemo.insertOne({"UserName":"Chris"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cbd6461de8cc557214c0e00")
}
> db.createArrayDemo.insertOne({"UserName":"David"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cbd6467de8cc557214c0e01")
}
> db.createArrayDemo.insertOne({"UserName":"Robert"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cbd646cde8cc557214c0e02")
}
> db.createArrayDemo.insertOne({"UserName":"Sam"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cbd6470de8cc557214c0e03")
}

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

> db.createArrayDemo.find().pretty();

This will produce the following output −

{ "_id" : ObjectId("5cbd6461de8cc557214c0e00"), "UserName" : "Chris" }
{ "_id" : ObjectId("5cbd6467de8cc557214c0e01"), "UserName" : "David" }
{ "_id" : ObjectId("5cbd646cde8cc557214c0e02"), "UserName" : "Robert" }
{ "_id" : ObjectId("5cbd6470de8cc557214c0e03"), "UserName" : "Sam" }

Case 1 − Create array with MongoDB.

If you want to create an array of field UserName and do not want the field _id, use the below query.

> db.createArrayDemo.find({},{_id:0}, {UserName:1}).toArray();

This will produce the following output −

[
   {
      "UserName" : "Chris"
   },
   {
      "UserName" : "David"
   },
   {
      "UserName" : "Robert"
   },
   {
      "UserName" : "Sam"
   }
]

Case 2 − Create array with MongoDB with field name_id only

If you want to create an array with field name _id only, use the below query.

> db.createArrayDemo.find({}, {_id:1}).toArray();

This will produce the following output −

[
   {
      "_id" : ObjectId("5cbd6461de8cc557214c0e00")
   },
   {
      "_id" : ObjectId("5cbd6467de8cc557214c0e01")
   },
   {
      "_id" : ObjectId("5cbd646cde8cc557214c0e02")
   },
   {
      "_id" : ObjectId("5cbd6470de8cc557214c0e03")
   }
]
raja
Published on 30-Apr-2019 10:45:09
Advertisements