Mongo 集合如下所示:
{
"_id" : ObjectId("5b693cbc032ee2fbb1d097f9"),
"name" : "PersonName1",
"email" : "dfgdfg@gmail.com",
"phone" : "46756456",
"address" : [
{
"Home" : "Home 1 person1"
},
{
"Work" : "Work1 person 1"
}
]
}
{
"_id" : ObjectId("5b6943b0032ee2fbb1d097fa"),
"name" : "PersoneName2",
"email" : "dfgdsfgdfg@gmail.com",
"phone" : "45645643",
"address" : [
{
"Home" : "Address of Home"
},
{
"Work" : "Address of Office"
}
]
}
对上述集合执行以下查询
db.subdocs.find({},{"address":{$elemMatch:{"Home":1}}});
上述查询的输出仅返回对象 ID:
{ "_id" : ObjectId("5b693cbc032ee2fbb1d097f9") },
{ "_id" : ObjectId("5b6943b0032ee2fbb1d097fa") }
如何让它同时显示我收藏的家庭住址?
最佳答案
您需要使用 $exists
使用 $elemMatch
查询元素运算符投影查找键是否存在于数组中
db.collection.find({},
{
address: {
$elemMatch: {
Home: {
$exists: true
}
}
}
})
试一试 here
关于arrays - 在不使用 RHS 作为 Mongo 中的引用的情况下查询对象数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51721075/