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

后端 未结 2 945
忘掉有多难
忘掉有多难 2020-12-11 13:51

I have collection entry like that

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

I want to fetc

相关标签:
2条回答
  • 2020-12-11 14:06

    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"
        }
    })
    
    0 讨论(0)
  • 2020-12-11 14:18

    Here is much simpler query;

    db.shapes.find({'shape.id':{$all:[1,2]},shape:{$size:2}});
    
    0 讨论(0)
提交回复
热议问题