gpt4 book ai didi

arrays - 在不使用 RHS 作为 Mongo 中的引用的情况下查询对象数组?

转载 作者:可可西里 更新时间:2023-11-01 10:46:16 25 4
gpt4 key购买 nike

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com