gpt4 book ai didi

mongodb - 在 $lookup 之后获取值作为元素数组

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

对于 MongoDB,当使用 $lookup 查询多个集合时,是否可以为 $lookup 中返回的字段获取仅值列表?

我不想要的是包含所有键/值的完整对象的列表。

数据:

failover_tool:PRIMARY> db.foo.find().pretty()
{
"_id" : ObjectId("5ce72e415267960532b8df09"),
"name" : "foo1",
"desc" : "first foo"
}
{
"_id" : ObjectId("5ce72e4a5267960532b8df0a"),
"name" : "foo2",
"desc" : "second foo"
}
failover_tool:PRIMARY> db.bar.find().pretty()
{
"_id" : ObjectId("5ce72e0c5267960532b8df06"),
"name" : "bar1",
"foo" : "foo1"
}
{
"_id" : ObjectId("5ce72e165267960532b8df07"),
"name" : "bar2",
"foo" : "foo1"
}
{
"_id" : ObjectId("5ce72e1d5267960532b8df08"),
"name" : "bar3",
"foo" : "foo2"
}

所需的查询输出

{
"_id" : ObjectId("5ce72e415267960532b8df09"),
"name" : "foo1",
"desc" : "first foo",
"bars" : ["bar1", "bar2"]
},
{
"_id" : ObjectId("5ce72e4a5267960532b8df0a"),
"name" : "foo2",
"desc" : "second foo",
"bars" : ["bar3"]
}

最近

这个查询看起来差不多了,但是它在 bars 字段中返回了太多数据:

db.foo.aggregate({
$lookup: {
from:"bar",
localField:"name",
foreignField: "foo",
as:"bars"
}
}).pretty()

最佳答案

只需在 name 字段中使用 .dot 符号

db.foo.aggregate([
{ "$lookup": {
"from": "bar",
"localField": "name",
"foreignField": "foo",
"as": "bars"
}},
{ "$addFields": { "bars": "$bars.name" }}
])

MongoPlayground

关于mongodb - 在 $lookup 之后获取值作为元素数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56284311/

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