Display only an element found in an array in MongoDB?

MongoDBDatabaseBig Data Analytics

To display only an element found in an array, use aggregate(). Let us create a collection with documents −

> db.demo204.insertOne(
...   {
...      "_id" : 101,
...      "Name" : "Chris",
...      "Age" : 23,
...      "details" : [
...         {
...            "id" : "1001",
...            "empId" : "John_1001",
...            "salary" : "50000",
...            "Technology" : "Java"
...         },
...         {
...            "id" : "1002",
...            "empId" : "John_1002"
...         },
...         {
...            "id" : "1003",
...            "empId" : "John_10003",
...            "salary" : "60000",
...            "Technology" : "MongoDB"
...         }
...      ]
...   }
...);
{ "acknowledged" : true, "insertedId" : 101 }

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

> db.demo204.find();

This will produce the following output −

{
   "_id" : 101, "Name" : "Chris", "Age" : 23, "details" : [
      { "id" : "1001", "empId" : "John_1001", "salary" : "50000", "Technology" : "Java" },
      { "id" : "1002", "empId" : "John_1002" },
      { "id" : "1003", "empId" : "John_10003", "salary" : "60000", "Technology" : "MongoDB" }
   ]
}

Following is the query to display only an element found in an array in MongoDB −

> db.demo204.aggregate(
...   [
...      { "$match": { "details.id": "1001" }},
...      { "$unwind": "$details" },
...      { "$match": { "details.id":"1001" }},
...      { "$project": { "Technology": "$details.Technology", "_id":0 }}
...   ]
...)

This will produce the following output −

{ "Technology" : "Java" }
raja
Published on 27-Mar-2020 10:37:34
Advertisements