gpt4 book ai didi

MongoDB 子文档投影

转载 作者:可可西里 更新时间:2023-11-01 10:00:59 29 4
gpt4 key购买 nike

需要一些基于子文档属性值的 Mongo 查询的帮助,同时还要抑制该子文档属性出现在结果中。

这是我的用户对象:

{
"username" : "abc",
"emails" : [
{
"address" : "abc1@email.com",
"default" : true
},
{
"address" : "abc2@email.com",
"default" : false
}
]
},
{
"username" : "xyz",
"emails" : [
{
"address" : "xyz1@email.com",
"default" : false
},
{
"address" : "xyz2@email.com",
"default" : true
}
]
}

我的目标是获得以下输出(带有“emails.default”:true 但结果中没有出现“emails.default”属性):

{
"username" : "abc",
"emails" : [
{
"address" : "abc1@email.com",
}
]
},
{
"username" : "xyz",
"emails" : [
{
"address" : "xyz2@email.com",
}
]
}

使用 $ 位置运算符:

collection.find({"emails.default":true}, {"username":1,"emails.$":1})

我得到了正确的电子邮件子文档,但我仍然得到了“emails.default”属性:

{
"username" : "abc",
"emails" : [
{
"address" : "abc1@email.com",
"default" : true
}
]
},
{
"username" : "xyz",
"emails" : [
{
"address" : "xyz2@email.com",
"default" : true
}
]
}

出于某种原因,当我使用此语句时:

collection.find({"emails.default":true}, {"username":1,"emails.address":1})

我得到以下结果(好像忽略了语句的查询部分)

{
"username" : "abc",
"emails" : [
{
"address" : "abc1@email.com",
},
{
"address" : "abc2@email.com",
}
]
},
{
"username" : "xyz",
"emails" : [
{
"address" : "xyz1@email.com",
},
{
"address" : "xyz2@email.com",
}
]
}

非常感谢,提前致谢。

最佳答案

使用位置运算符(在 MongoDB 2.6 中),您不能有选择地排除要匹配的数组元素的字段。

但是,您可以使用 MongoDB 2.2+ 中的聚合框架来实现您想要的结果:

db.user.aggregate(

// Match on relevant documents to optimize query
{ $match: {
username: "abc"
}},

// Convert the "emails" address into a stream of documents
{ $unwind: "$emails" },

// Only include the emails with default:true
{ $match: {
"emails.default" : true
}},

// Project the desired fields
{ $project: {
_id : 0,
username: 1,
"emails.address": 1
}}
)

示例结果:

{
"username" : "abc",
"emails" : {
"address" : "abc1@email.com"
}
}

关于MongoDB 子文档投影,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20726731/

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