D. Ramsook
D. Ramsook

Reputation: 71

How to query certain elements of an array of objects? (mongodb)

say I have a mongo DB collection with records as follows:

{
email: "person1@gmail.com",
plans: [
         {planName: "plan1", dataValue = 100},
         {planName: "plan2", dataValue = 50}
       ]
},
{
email: "person2@gmail.com",
plans: [
         {planName: "plan3", dataValue = 25},
         {planName: "plan4", dataValue = 12.5}
       ]
}

and I want to query such that only the dataValue returns where the email is "person1@gmail.com" and the planName is "plan1". How would I approach this?

Upvotes: 0

Views: 48

Answers (1)

Montgomery Watts
Montgomery Watts

Reputation: 4034

You can accomplish this using the Aggregation Pipeline.

The pipeline may look like this:

db.collection.aggregate([
  { $match: { "email" :"person1@gmail.com", "plans.planName": "plan1" }},
  { $unwind: "$plans" },
  { $match: { "plans.planName": "plan1" }},
  { $project: { "_id": 0, "dataValue": "$plans.dataValue" }}
])

The first $match stage will retrieve documents where the email field is equal to person1@gmail.com and any of the elements in the plans array has a planName equal to plan1.

The second $unwind stage will output one document per element in the plans array. The plans field will now be an object containing a single plan object.

In the third $match stage, the unwound documents are further matched against to only include documents with a plans.planName of plan1. Finally, the $project stage excludes the _id field and projects a single dataValue field with a value of plans.dataValue.

Note that with this approach, if the email field is not unique you may have multiple documents consist with just a dataValue field.

Upvotes: 1

Related Questions