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") }
如何显示收藏夹中的两个家庭住址?
答案 0 :(得分:0)
您需要对$exists
投影使用$elemMatch
查询元素运算符,以查找键是否存在于数组中
db.collection.find({},
{
address: {
$elemMatch: {
Home: {
$exists: true
}
}
}
})
尝试here
答案 1 :(得分:0)
您的问题是投影确实不匹配,
您的查询尝试找到address.Home = 1
,并且您需要包含address.Home
(存在Home
)的项目
然后,只需执行查询...
db.subdocs.find({},{"address": { $elemMatch: { "Home" : { $exists: true } } } );
或者如果您需要“主页”包含某些内容
db.subdocs.find({},{"address": { $elemMatch: { "Home" : { $regex: "person" } } } );
答案 2 :(得分:0)
db.getCollection("subdocs").find({
address: {
$elemMatch: {
Home: {
$exists: true
}
}
}
}, {
'address.$.Home': 1
})