Querying object's field array values in MongoDB?

MongoDBDatabaseBig Data Analytics

Query object’s field array value using arrayFieldName along with value. Let us create a collection with documents −

> db.demo295.insertOne({"status":["Active","Inactive"]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e4d4ea65d93261e4bc9ea39")
}
> db.demo295.insertOne({"status":["Yes","No"]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e4d4eb15d93261e4bc9ea3a")
}

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

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

This will produce the following output −

{
   "_id" : ObjectId("5e4d4ea65d93261e4bc9ea39"),
   "status" : [
      "Active",
      "Inactive"
   ]
}
{
   "_id" : ObjectId("5e4d4eb15d93261e4bc9ea3a"),
   "status" : [
      "Yes",
      "No"
   ]
}

Following is how to query object's field array values in MongoDB −

> db.demo295.find({status:"Inactive"});

This will produce the following output −

{ "_id" : ObjectId("5e4d4ea65d93261e4bc9ea39"), "status" : [ "Active", "Inactive" ] }
raja
Published on 01-Apr-2020 10:44:14
Advertisements