Retrieve only the queried element in an object array in MongoDB collection?

MongoDBDatabaseBig Data Analytics

You can use projection operator $elemMatch to filter in queried element in an object array in MongoDB collection. To retrieve only the queried element in an object array in MongoDB, let us first create a collection with documents object array.

The query is as follows:

> db.objectArray.insert({"Persons":[
   {"PersonName":"Adam","PersonSalary":25000},{"PersonName":"Larry","PersonSalary":27000
   }]});
   WriteResult({ "nInserted" : 1 })
> db.objectArray.insert({"Persons":[
   {"PersonName":"David","PersonSalary":32000},{"PersonName":"Carol","PersonSalary":77000
   }]});
   WriteResult({ "nInserted" : 1 })

Now you can display all the documents with the help of find(). The query is as follows:

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

The following is the output:

{
   "_id" : ObjectId("5c6bfadc68174aae23f5ef53"),
   "Persons" : [
      {
         "PersonName" : "Adam",
         "PersonSalary" : 25000
      },
      {
         "PersonName" : "Larry",
         "PersonSalary" : 27000
      }
   ]
}
{
   "_id" : ObjectId("5c6bfb0968174aae23f5ef54"),
   "Persons" : [
      {
         "PersonName" : "David",
         "PersonSalary" : 32000
      },
      {
         "PersonName" : "Carol",
         "PersonSalary" : 77000
      }
   ]
}

Here is the query to retrieve only the queried element in an object array in MongoDB. Here In _id:0 is added to exclude the id property(do not show the _id property):

> db.objectArray.find({"Persons.PersonSalary":25000}, {
_id:0,Persons:{$elemMatch:{"PersonSalary":25000}}}).pretty();

The following is the output:

{
   "Persons" : [
      {
         "PersonName" : "Adam",
         "PersonSalary" : 25000
      }
   ]
}

Alternate way to do the above task is with the help of projection operator $. The query is as follows:

> db.objectArray.find({"Persons.PersonSalary":25000}, { _id:0,'Persons.$':1}).pretty();

The following is the output:

{
   "Persons" : [
      {
         "PersonName" : "Adam",
         "PersonSalary" : 25000
      }
   ]
}
raja
Published on 18-Mar-2019 10:56:18
Advertisements