MongoDB: Match multiple array elements

前端 未结 1 1657
名媛妹妹
名媛妹妹 2020-12-17 03:18

I have a collection with next data:

db.MyCollection.insert({ 
        id: 1, 
        Location: [ 1, 1 ],
        Properties: [ { Type: 1, Value: \"a\" }, {          


        
相关标签:
1条回答
  • 2020-12-17 03:57

    In a case like this where you want the docs that include a specific set of array elements, you can use the $all operator:

    db.MyCollection.find(
    { 
        Location: { "$within": { "$center": [ [1, 1], 5 ] } },
        Properties: {
            $all: [
                {$elemMatch: { Type: 1, Value: "a" }},
                {$elemMatch: { Type: 2, Value: "b" }}
            ]
        }
    })
    

    To do it without the $all operator you could use:

    db.MyCollection.find(
    { 
        Location: { "$within": { "$center": [ [1, 1], 5 ] } },
        $and: [
            { Properties: {
                $elemMatch: { Type: 1, Value: "a" }
            }},
            { Properties: {
                $elemMatch: { Type: 2, Value: "b" }
            }}
        ]
    })
    
    0 讨论(0)
提交回复
热议问题