MongoDB query check if value in array property?


You can use $in operator to check if a value is in an array or not. Let us first create a collection with documents −

> db.valueInArrayDemo.insertOne({"UserName":"John","UserMessage":["Hi","Hello","Bye"]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd684cf7924bb85b3f48959")
}
> db.valueInArrayDemo.insertOne({"UserName":"Larry","UserMessage":["Thank You","Amazing","Nice"]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd684d27924bb85b3f4895a")
}
>db.valueInArrayDemo.insertOne({"UserName":"Carol","UserMessage":["Awesome","Bye","Cool"]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd684d87924bb85b3f4895b")
}

Following is the query to display all documents from a collection with the help of find() method −

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

This will produce the following output −

{
   "_id" : ObjectId("5cd684cf7924bb85b3f48959"),
   "UserName" : "John",
   "UserMessage" : [
      "Hi",
      "Hello",
      "Bye"
   ]
}
{
   "_id" : ObjectId("5cd684d27924bb85b3f4895a"),
   "UserName" : "Larry",
   "UserMessage" : [
      "Thank You",
      "Amazing",
      "Nice"
   ]
}
{
   "_id" : ObjectId("5cd684d87924bb85b3f4895b"),
   "UserName" : "Carol",
   "UserMessage" : [
      "Awesome",
      "Bye",
      "Cool"
   ]
}

Following is the query to check if a specific value is in an array with $in −

> db.valueInArrayDemo.find({UserMessage:{$in:["Bye"]}});

This will produce the following output −

{ "_id" : ObjectId("5cd684cf7924bb85b3f48959"), "UserName" : "John", "UserMessage" : [ "Hi", "Hello", "Bye" ] }
{ "_id" : ObjectId("5cd684d87924bb85b3f4895b"), "UserName" : "Carol", "UserMessage" : [ "Awesome", "Bye", "Cool" ] }

Updated on: 30-Jul-2019

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements