justin
justin

Reputation: 661

How to aggregate queries in mongodb

I have a document collection that look like the following:

{
  name : "tester"
  , activity: [
    {
      gear: "glasses"
      where: "outside"    
    }
    , {
      gear: "hat"
      , where: "inside"
    }
    , {
      gear: "glasses"
      , where: "car"
    }
  ]
}

How do I query the collection to return only documents with multiple activities that contain the value of "gear":"glasses"?

Thanks!

Upvotes: 2

Views: 1243

Answers (3)

roman
roman

Reputation: 117345

I think it's possible to do without aggregation framework, if you need full document filtered by your condition:

db.collection.find({
    "activity": {$elemMatch: {gear:"glasses"}},
    "activity.1" : {$exists: 1}
})

Upvotes: 3

Jetson John
Jetson John

Reputation: 3829

You can also try this:

db.collection.find( { activity: { $elemMatch: { gear: "glasses" } } )

Upvotes: 1

Chris Winslett
Chris Winslett

Reputation: 836

This is going to be ugly with aggregation framework, but it can be done:

db.collection.aggregate(
  {$match: {"activity.gear": "glasses"}},
  {$unwind: "$activity"},
  {$group: {
    _id: {_id: "$_id", name: "$name"},
    _count: {$sum: {$cond: [{$eq: ["glasses", "$activity.gear"]}, 1, 0]}}
  }},
  {$match: {_count: {$gt: 1}}}
)

When analyzing the above query, I would recommend walking through step. Start with just the "$match", the the "$match" and "$unwind". And so one. You will see how each step works.

The response is not the full document. If you are looking for the full document, include a $project step that passes through a dummy activity, and reconstruct the full document on the output.

Upvotes: 2

Related Questions