Query for values (not objects) in list with MongoDB

MongoDBDatabaseBig Data Analytics

To query for values in list, use positional operator($) in MongoDB. Let us create a collection with documents −

> db.demo628.insertOne({id:1,Name:["Chris","David","John"]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e9ae7ea6c954c74be91e6b6")
}
> db.demo628.insertOne({id:1,Name:["Carol","Sam"]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e9ae7f26c954c74be91e6b7")
}
> db.demo628.insertOne({id:2,Name:["Mike","Sam","John"]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e9ae8056c954c74be91e6b8")
}

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

> db.demo628.find();

This will produce the following output −

{ "_id" : ObjectId("5e9ae7ea6c954c74be91e6b6"), "id" : 1, "Name" : [ "Chris", "David", "John" ] }
{ "_id" : ObjectId("5e9ae7f26c954c74be91e6b7"), "id" : 1, "Name" : [ "Carol", "Sam" ] }
{ "_id" : ObjectId("5e9ae8056c954c74be91e6b8"), "id" : 2, "Name" : [ "Mike", "Sam", "John" ] }

Query for values (not objects) in list −

> db.demo628.find({"Name":"John"}, {"id":1, "Name.$":1});

This will produce the following output −

{ "_id" : ObjectId("5e9ae7ea6c954c74be91e6b6"), "id" : 1, "Name" : [ "John" ] }
{ "_id" : ObjectId("5e9ae8056c954c74be91e6b8"), "id" : 2, "Name" : [ "John" ] }
raja
Published on 12-May-2020 07:13:09
Advertisements