我正在尝试使用 node.js MongoDB 驱动程序向查找结果添加一个字段。用户有两种提要 1. 他或她自己的提要和 2. 共享提要。所以我需要同时获得两者,然后将它们结合起来。这是我原来的查询,效果很好:
client.db('atlas').collection('users').aggregate([
{ $match: { user_id: userId } },
{
$lookup: {
from: 'feeds',
localField: "user_id",
foreignField: "user_id",
as: "feeds"
}
},
{
$lookup: {
from: 'shares',
localField: 'email',
foreignField: "share",
as: "shares"
}
},
{
$lookup: {
from: 'feeds',
localField: 'shares.feed_id',
foreignField: "_id",
as: "shared_feeds"
}
},
{
$addFields: { 'shared_feeds.share': true }
},
{
$project: {
user_id: 1,
first_name: 1,
last_name: 1,
email: 1,
feeds: { $concatArrays: [ '$feeds', '$shared_feeds' ] }
}
}
])
但我想在“提要”的第二次查找中添加一个字段,因此我尝试使用如下管道:
{
$lookup: {
from: 'feeds',
let: { shareId: '$shares.feed_id' },
pipeline: [
{ $match: { '_id': ObjectId('$$shareId') } }
],
as: "shared_feeds"
}
}
但我无法让比赛发挥作用ObjectId
。该变量似乎不起作用。我究竟做错了什么?
样本集合:
用户:
[
{
"_id" : ObjectId("5e970a1f797c08e70ce4e2f6"),
"user_id" : "testuserid",
"first_name" : "Jacopo",
"last_name" : "Belbo",
"email" : "[email protected] /cdn-cgi/l/email-protection"
}
]
feeds:
[
{
"_id" : ObjectId("5f29b02318ecbf0083f01f1e"),
"name" : "test csv",
"user_id" : "auth0|5eac6faa1cc1ac0c147b5b16",
"type" : "feed",
"created_at" : ISODate("2020-08-04T18:59:47.640Z"),
"updated_at" : ISODate("2020-08-04T18:59:47.640Z")
},
{
"_id" : ObjectId("5f29b05d18ecbf0083f01f1f"),
"name" : "typtap-small",
"user_id" : "auth0|5f1b2da0e60194003d714680",
"url" : "http://localstack:4572/atlas/usertes",
"type" : "feed",
"created_at" : ISODate("2020-08-04T19:00:45.886Z"),
"updated_at" : ISODate("2020-08-04T19:00:45.886Z")
}
]
shares:
[
{
"_id" : ObjectId("5f29b07318ecbf0083f01f20"),
"feed_id" : ObjectId("5f29b05d18ecbf0083f01f1f"),
"share" : "[email protected] /cdn-cgi/l/email-protection",
"type" : "share",
"recipient" : "email",
"created_at" : ISODate("2020-08-04T19:01:07.668Z"),
"updated_at" : ISODate("2020-08-04T19:01:07.668Z")
}
]