How do I work with array fields in MongoDB to match all?

MongoDBDatabaseBig Data Analytics

To match all in MongoDB, use $all. The $all operator selects the documents where the value of a field is an array that contains all the specified elements. Let us create a collection with documents −

> db.demo695.insertOne({"ListOfValues":[100,200,500,800]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ea6d4c4551299a9f98c938f")
}
> db.demo695.insertOne({"ListOfValues":[1000,200,4000]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ea6d4cf551299a9f98c9390")
}

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

> db.demo695.find();

This will produce the following output −

{ "_id" : ObjectId("5ea6d4c4551299a9f98c938f"), "ListOfValues" : [ 100, 200, 500, 800 ] }
{ "_id" : ObjectId("5ea6d4cf551299a9f98c9390"), "ListOfValues" : [ 1000, 200, 4000 ] }

Following is the query to work with array field and match all −

> db.demo695.find({"ListOfValues":{$all:[1000,200,4000]}});

This will produce the following output −

{ "_id" : ObjectId("5ea6d4cf551299a9f98c9390"), "ListOfValues" : [ 1000, 200, 4000 ] }
raja
Published on 14-May-2020 12:51:36
Advertisements