1

I have a mongodb collection with structure like that:

[
  {
    name: "name1",
    instances: [{value:1, score:2}, {value:2, score:5}, {value:2.5, score:9}]
  },
  {
    name: "name2",
    instances: [{value:6, score:3}, {value:1, score:6}, {value:3.7, score:5.2}]
  }
]

When I want to get all the data from a document, I use aggregate because I want each instance returned as a separate document:

db.myCollection.aggregate([{$match:{name:"name1"}}, {$unwind:"$instances"}, {$project:{name:1, value:"$instances.value", score:"$instances.score"}}])

And everything works like I want it to.

Now for my question: I want to filter the returned data by score or by value. For example, I want an array of all the subdocuments of name1 which have a value greater or equal to 2. I tried to add to the $match object 'instances.value':{$gte:2}, but it didn't filter anything, and I still get all 3 documents for this query.

Any ideas?

3
  • Help me to understand your problem clearly, do you have a sample expected output? Commented Apr 14, 2015 at 7:43
  • 1
    @chridam, expected result: [{name:"name1", value:2, score:5}, {name:"name1", value:2.5, score:9}] Commented Apr 14, 2015 at 7:47
  • 1
    Cheers, I believe @yogesh got it right. Commented Apr 14, 2015 at 7:59

1 Answer 1

2

After unwinding instances then again used $match as below

    db.collectionName.aggregate({
    "$match": {
    "name": "name1"
    }
}, {
    "$unwind": "$instances"
}, {
    "$match": {
    "instances.value": {
        "$gte": 2
    }
    }
}, {
    $project: {
    name: 1,
    value: "$instances.value",
    score: "$instances.score"
    }
})

Or if you tried $match after project then used as below

 db.collectionName.aggregate([{
     $match: {
     name: "name1"
     }
 }, {
     $unwind: "$instances"
 }, {
     $project: {
     name: 1,
     value: "$instances.value",
     score: "$instances.score"
     }
 }, {
     "$match": {
     "value": {
         "$gte": 2
     }
     }
 }])
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.