Filter specific values from a MongoDB document

MongoDBDatabaseBig Data Analytics

To filter specific values, use $filter in MongoDB. Let us create a collection with documents −

> db.demo751.insertOne(
...    {
...       _id: 101,
...       details: [
...          { Name: "Robert", id:110,Age:21},
...          { Name: "Rae", id:110,Age:22},
...          {Name: "Ralph", id:116,Age:23}
...       ]
...    }
... );
{ "acknowledged" : true, "insertedId" : 101 }

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

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

This will produce the following output −

{
   "_id" : 101,
   "details" : [
      {
         "Name" : "Robert",
         "id" : 110,
         "Age" : 21
      },
      {
         "Name" : "Rae",
         "id" : 110,
         "Age" : 22
      },
      {
         "Name" : "Ralph",
         "id" : 116,
         "Age" : 23
      }
   ]
}

Following is the query to filter −

> db.demo751.aggregate([
...    {
...       $addFields: {
...          details: {
...             $let: {
...                vars: {
...       filtered: { $filter: { input: "$details", as: "out", cond: { $eq: [ "$$out.id", 110 ] } } }
...                },
...                in: { $slice: [ "$$filtered", -1 ] }
...             }
...          }
...       }
...    }
... ])

This will produce the following output −

{ "_id" : 101, "details" : [ { "Name" : "Rae", "id" : 110, "Age" : 22 } ] }
raja
Published on 30-Jun-2020 11:44:52
Advertisements