4

here is the example

> db.test.insert({ name: 'test', values: [ { check: true }, { check: false } ] })
> db.find({ values.check: true })[0]

so I get both true and false check:

{
        "_id" : ObjectId("50e22046dc278908f3a38a8e"),
        "name" : "test",
        "values" : [
                {
                        "check" : true
                },
                {
                        "check" : false
                }
        ]
}

and I want to get this:

{
        "_id" : ObjectId("50e22046dc278908f3a38a8e"),
        "name" : "test",
        "values" : [
                {
                        "check" : true
                }
        ]
}

is there any filter commands for this?

Clifford
  • 88,407
  • 13
  • 85
  • 165
Nick Sanders
  • 693
  • 2
  • 9
  • 19

3 Answers3

5

You can use the $ projection operator to include just the first values array element that matched the query:

 db.test.find({ 'values.check': true }, {name: 1, 'values.$': 1})

returns:

{
    "_id": ObjectId("50e22046dc278908f3a38a8e"), 
    "name": "test", 
    "values": [ { "check": true } ] }
JohnnyHK
  • 305,182
  • 66
  • 621
  • 471
  • thanks for the answer. is there a chance to match not just one but all values that is true? – Nick Sanders Dec 31 '12 at 05:12
  • I've just heard about $elemMatch I think that's the answer – Nick Sanders Dec 31 '12 at 05:13
  • $eleMatch also only returns the first matched element. See [this post](http://stackoverflow.com/questions/3985214/mongodb-extract-only-the-selected-item-in-array/12241930) for details on how to use the aggregation framework to include all matching elements. – JohnnyHK Dec 31 '12 at 05:22
0
$fetchcode = "Fetch an array from the mongo db"
   foreach ($fetchcode as $mainkey => $mainVariable) {
        foreach($mainVariable as $key2 => $doc2)
        {
            if($key2 == "check"){
                if($doc2 == "true")
                {
                   //Your Function Here
                }
            }
        }
    }

You can try this

Eugene Tang
  • 83
  • 2
  • 8
0
> db.test.aggregate(
{ $unwind: "$values" },
{ $match: { "values.check": true } }
).result

[
        {
                "_id" : ObjectId("50e22046dc278908f3a38a8e"),
                "name" : "test",
                "values" : {
                        "check" : true
                }
        }
]
Nick Sanders
  • 693
  • 2
  • 9
  • 19