MongoDB “$and” operator for subcollection to fetch a document?


To fetch a document, use $in, instead of $and in MongoDB. Let us first create a collection with documents −

> db.demo83.insertOne(
... {
...    "Details":[
...       {
...          "Name":"Chris",
...          "Subject":[
...             "MySQL",
...             "MongoDB"
...          ]
...       },
...       {
...          "Name":"David",
...          "Subject":[
...          "Java",
...          "C"
...          ]
...       }
...    ]
... }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e2bfd2271bf0181ecc422a3")
}
> db.demo83.insertOne(
... {
...    "Details":[
...       {
...          "Name":"Bob",
...          "Subject":[
...          "C++",
...          "Python"
...          ]
...       },
...       {
...          "Name":"John",
...          "Subject":[
...             "Spring",
...             "Hibernate"
...          ]
...       }
...    ]
... }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e2bfd4571bf0181ecc422a4")
}

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

> db.demo83.find();

This will produce the following output −

{
   "_id" : ObjectId("5e2bfd2271bf0181ecc422a3"), "Details" : [
      { "Name" : "Chris", "Subject" : [ "MySQL", "MongoDB" ] },
      { "Name" : "David", "Subject" : [ "Java", "C" ] }
   ]
}
{
   "_id" : ObjectId("5e2bfd4571bf0181ecc422a4"), "Details" : [
      { "Name" : "Bob", "Subject" : [ "C++", "Python" ] },
      { "Name" : "John", "Subject" : [ "Spring", "Hibernate" ] }
   ]
}

Following is the query to find a document using $in −

> db.demo83.find({ "Details" : { "$elemMatch" : {"Name" :"Chris" , "Subject":{"$in":["MongoDB"]}}}});

This will produce the following output −

{
   "_id" : ObjectId("5e2bfd2271bf0181ecc422a3"), "Details" : [
      { "Name" : "Chris", "Subject" : [ "MySQL", "MongoDB" ] },
      { "Name" : "David", "Subject" : [ "Java", "C" ] }
   ] 
}

Updated on: 30-Mar-2020

342 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements