MongoDb 聚合查找不产生结果,而foreignField 为_id。
我有两个集合说 users
和 discussions
示例 users
数据:
[{
_id: 5f9c50dcfac1f091400225e3,
email: 'Peter.Parker@gmail.com',
details: { fname: 'Peter Test', lname: 'Fulton' },
},
{
_id: 5fa432bfb91fab7db60c70eb,
email: 'Spidy@xxx.com',
details: { fname: 'Frodo', lname: 'Baggins' },
},
{
_id: 5fa8ec7d3ce22610e5d15190,
email: 'tommy@xxx.com',
details: { fname: 'Tommy', lname: 'test' },
},
{
_id: 5fc38bb0b3683651be970180,
email: 'jerry@xxx.io',
},
{
_id: 5fd2340cc443d155ab38383b,
email: 'Dexter@xxx.io',
details: { fname: 'Dexter', lname: 'Lab' },
}]
示例 discussions
数据:
{_id: ObjectId("5fb2abd6b14fa5683979df58"),
tags: [ 'javascritp', 'css', 'html' ],
title: 'Why is this inline-block element pushed downward?',
post: 'Test Post',
learnerId: ObjectId("5f9c50dcfac1f091400225e3"),
}
此处 _id
的“users
”与“learnerId
”的“discussions
”相关联。
我的聚合查询如下所示。
db.users.aggregate([
{ $project: { "details.fname": 1, "details.lname":1,email:1, _id:1}},
{$lookup: {
from: "discussions",
localField: "learnerId",
foreignField: "_id",
as: "discussions"
}}
])
此处为 'Peter Test'
,_id 5f9c50dcfac1f091400225e3
与 discussions LeanerId
相关联。但我预计讨论会出现在我的结果中。我在所有用户集合中看到空的讨论数组。
[{
_id: 5f9c50dcfac1f091400225e3,
email: 'Peter.Parker@gmail.com',
details: { fname: 'Peter Test', lname: 'Fulton' },
discussions: []
},
{
_id: 5fa432bfb91fab7db60c70eb,
email: 'Spidy@xxx.com',
details: { fname: 'Frodo', lname: 'Baggins' },
discussions: []
},
{
_id: 5fa8ec7d3ce22610e5d15190,
email: 'tommy@xxx.com',
details: { fname: 'Tommy', lname: 'test' },
discussions: []
},
{
_id: 5fc38bb0b3683651be970180,
email: 'jerry@xxx.io',
discussions: []
},
{
_id: 5fd2340cc443d155ab38383b,
email: 'Dexter@xxx.io',
details: { fname: 'Dexter', lname: 'Lab' },
discussions: []
}]
你能指出我的汇总查询有什么问题吗?
答案 0 :(得分:1)
您的 localField 和 foreignField 不匹配
db.users.aggregate([
{
$project: {
"details.fname": 1,
"details.lname": 1,
email: 1,
_id: 1
}
},
{
$lookup: {
from: "discussions",
localField: "_id",
foreignField: "learnerId",
as: "discussions"
}
}
])