在 $lookup 之后获取值作为元素数组 [英] Get values as array of elements after $lookup
本文介绍了在 $lookup 之后获取值作为元素数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
对于 MongoDB,当使用 $lookup
查询多个集合时,是否可以为 $lookup
中返回的字段获取仅值列表?
For MongoDB, when using $lookup
to query more than one collection, is it possible to get a values-only list for a field returned in the $lookup
?
我不想要的是包含所有键/值的完整对象的列表.
What I don't want is a list of the full object with all its key/values.
数据:
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
字段中返回了太多数据:
This query seems like it's almost there, but it returns too much data in the bars
field:
db.foo.aggregate({
$lookup: {
from:"bar",
localField:"name",
foreignField: "foo",
as:"bars"
}
}).pretty()
推荐答案
只需在 name
字段中使用 .dot
表示法
Just use .dot
notation with the name
field
db.foo.aggregate([
{ "$lookup": {
"from": "bar",
"localField": "name",
"foreignField": "foo",
"as": "bars"
}},
{ "$addFields": { "bars": "$bars.name" }}
])
这篇关于在 $lookup 之后获取值作为元素数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文