cuốn sách gpt4 ai đã làm

javascript - 如何从另一个集合中只检索几个字段

In lại Tác giả: Hồ Xil 更新时间:2023-11-01 09:53:42 25 4
mua khóa gpt4 Nike

我有两个收藏

Collection_foo :

{
cid:'1234',
'foo':'bar',
some 10+ fields...
}

收藏栏:

{
cid:'1234',
'foobar':'barfoo',
some 10+ fields...
}

我要加入这个收藏

我尝试使用 $lookup、$unwind、$project

aggregate([
{
$lookup:{
from: 'Collection_bar',
localField: 'cid',
foreignField: 'cid',
as: 'collection_foo_bar',
}
},
{ $unwind :'collection_foo_bar' },
{
$project : {
'foobar':'collection_foo_bar.foobar',
collection_foo_bar : 0 //
}
}
])

我也试过,但是报错

{ 
$project : {
'foobar':'collection_foo_bar.foobar',
collection_foo_bar : 0
}
}

现在我明白了

{
'foobar':'barfoo'

}

我想要这个

{
cid:'1234',
'foo':'bar',
some 10+ fields...,
'foobar':'barfoo'
}

只有第 2 个集合中的 1 个字段。

câu trả lời hay nhất

请看看这个。变体 1。

db.Collection_foo.aggregate([
{
$lookup:{
from: "Collection_bar",
localField: "cid",
foreignField:"cid",
as: "collection_foo_bar"
},
},
{ $unwind :'$collection_foo_bar' },
{
$replaceRoot: {
newRoot: {
$mergeObjects: [ "$$ROOT",{foobar:"$collection_foo_bar.foobar"}]
}
}
},
{ $project: { collection_foo_bar: 0 } }

])

变体 2

db.Collection_foo.aggregate([
{
$lookup:{
from: "Collection_bar",
localField: "cid",
foreignField:"cid",
as: "collection_foo_bar"
},
},
{ $unwind :'$collection_foo_bar' },
{
$addFields: {foobar:"$collection_foo_bar.foobar"}
},
{ $project: { collection_foo_bar: 0 } }
])

结果

{
"_id" : ObjectId("5c51a1479b70d343fb47d3ae"),
"cid" : "1234",
"foo" : "bar",
"f1" : 1.0,
"f23" : 2,
"f33" : 3,
"foobar" : "barfoo1111"
}

第二个集合中的“foobar”和第一个集合中的其他字段。

关于javascript - 如何从另一个集合中只检索几个字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54441053/

25 4 0
Hồ Xil
Hồ sơ

Tôi là một lập trình viên xuất sắc, rất giỏi!

Nhận phiếu giảm giá taxi Didi miễn phí
Phiếu giảm giá taxi Didi
Chứng chỉ ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com
Xem sitemap của VNExpress