0

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

{
email: "[email protected]",
plans: [
         {planName: "plan1", dataValue = 100},
         {planName: "plan2", dataValue = 50}
       ]
},
{
email: "[email protected]",
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 "[email protected]" and the planName is "plan1". How would I approach this?

1 Answer 1

1

You can accomplish this using the Aggregation Pipeline.

The pipeline may look like this:

db.collection.aggregate([
  { $match: { "email" :"[email protected]", "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 [email protected] 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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.