Find exactly match array or having all value of array in MongoDb

折月煮酒 提交于 2020-01-03 04:56:05

问题


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


回答1:


Here is much simpler query;

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



回答2:


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"
    }
})


来源:https://stackoverflow.com/questions/28735439/find-exactly-match-array-or-having-all-value-of-array-in-mongodb

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!