Querying array of Embedded Documents in MongoDB based on Range?

MongoDBDatabaseBig Data Analytics

To query an array of embedded documents based on range, use aggregate(). Let us create a collection with documents −

> db.demo346.insertOne(
...    {
...       _id: 101,
...       userDetails: [
...          { UserName: "Chris", Score:78},
...          { UserName: "David", Score:68},
...          { UserName: "Bob", Score:88}
...       ]
...    }
... );
{ "acknowledged" : true, "insertedId" : 101 }
> db.demo346.insertOne(
...    {
...       _id: 102,
...       userDetails: [
...          { UserName: "Mike", Score:92},
...          { UserName: "Sam", Score:62},
...          { UserName: "Carol", Score:97}
...       ]
...    }
... );
{ "acknowledged" : true, "insertedId" : 102 }

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

> db.demo346.find();

This will produce the following output −

{
   "_id" : 101, "userDetails" : [
      { "UserName" : "Chris", "Score" : 78 },
      { "UserName" : "David", "Score" : 68 },
      { "UserName" : "Bob", "Score" : 88 }
   ]
}
{
   "_id" : 102, "userDetails" : [
      { "UserName" : "Mike", "Score" : 92 },
      { "UserName" : "Sam", "Score" : 62 },
      { "UserName" : "Carol", "Score" : 97 }
   ] 
}

Following is how to query an array of embedded documents in MongoDB based on Range −

> db.demo346.aggregate([
...    { "$match": { "$expr": { "$gte": [{ "$size": { "$ifNull": ["$userDetails", []] } }, 1] }}},
...    { "$addFields": {
...          "userDetails": {
...          "$filter": {
...             "input": { "$ifNull": ["$userDetails", []] },
...             "cond": {
...                "$and": [
...                   { "$gte": ["$$this.Score", 80] },
...                   { "$lte": ["$$this.Score", 99] }
...                ]
...             }
...          }
...       }
...    }}
... ])

This will produce the following output −

{ "_id" : 101, "userDetails" : [ { "UserName" : "Bob", "Score" : 88 } ] }
{ "_id" : 102, "userDetails" : [ { "UserName" : "Mike", "Score" : 92 }, { "UserName" : "Carol", "Score" : 97 } ] }
raja
Published on 02-Apr-2020 11:12:30
Advertisements