如何保持mongodb中数组元素之间的相关性?

时间:2017-01-26 11:46:08

标签: mongodb

假设我在mongo中有一个student collection,如下所示:

{
"_id":1,
"name":"John"
"address":[
        {
         "country":"US",
         "city":"Newyork"
        },
        {
         "country":"Canada",
         "city":"Ottawa"
        }
        ]
}

现在,问题是这个student将满足带有过滤器的查询:

"address.country"="US" && "address.city"="Ottawa"

所以,correlation between country and city is lost在这里。上述学生应仅对以下过滤器提出满意的查询:

->    "address.country"="US" && "address.city"="Newyork"
->    "address.country"="Canada" && "address.city"="Ottawa"

如何在mongo中保持或保持这种相关性?

1 个答案:

答案 0 :(得分:1)

您可以使用$elemMatch

实现此目的
db.students.find(
   { address: { $elemMatch: { country: "US", city: "Newyork" } } }
)