0

I have collection entry like that

[
 {
    shape : [{id:1,status:true},{id:2,status:false}]
 },
 {
    shape : [{id:1,status:true}]
 }
]

I want to fetch data which exactly match array , means contain all ele. of array.

Ex. where shape.id = [1,2] / [ {id: [1,2] } ] (any one is prefer)

then it should return only

[
 {
    shape : [{id:1,status:true},{id:2,status:false}]
 }
]

So help me if is there any native mongodb query .

Thanks

--ND

Nishchit
  • 18,284
  • 12
  • 54
  • 81
  • 1
    You need to make use of the `$elemMatch` operator: http://docs.mongodb.org/manual/reference/operator/query/elemMatch/ – ZeMoon Feb 26 '15 at 06:09

2 Answers2

6

Here is much simpler query;

db.shapes.find({'shape.id':{$all:[1,2]},shape:{$size:2}});
Safi
  • 1,112
  • 7
  • 9
1

If mongo documents as below

    {
    "_id" : ObjectId("54eeb68c8716ec70106ee33b"),
    "shapeSize" : [
        {
            "shape" : [
                {
                    "id" : 1,
                    "status" : true
                },
                {
                    "id" : 2,
                    "status" : false
                }
            ]
        },
        {
            "shape" : [
                {
                    "id" : 1,
                    "status" : true
                }
            ]
        }
    ]
}

Then used below aggregation to match the criteria

        db.collectionName.aggregate({
    "$unwind": "$shapeSize"
}, {
    "$match": {
    "$and": [{
        "shapeSize.shape.id": 2
    }, {
        "shapeSize.shape.id": 1
    }]
    }
}, {
    "$project": {
    "_id": 0,
    "shape": "$shapeSize.shape"
    }
})
Neo-coder
  • 7,715
  • 4
  • 33
  • 52