mongodb - _id 的 Mongodb 聚合查找不起作用
问题描述
MongoDb 聚合查找未产生结果,而外域字段为 _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'
与 _id5f9c50dcfac1f091400225e3
链接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: []
}]
您能在这里指出我的汇总查询有什么问题吗?
解决方案
您的 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"
}
}
])
工作Mongo游乐场
推荐阅读
- java - 找不到 BLE 设备
- sql - postgres:如何选择一个范围内的每个值?
- php - 无法按属性访问集合 Laravel 5.8
- html - 如何在 rmarkdwn html 中进行分页?
- node.js - 用于 QR 码的 Google Vision API 不在移动平台上
- java - 我们如何在 RecyclerView 中处理来自多个项目视图的点击?
- excel - 排除多个组合框中的双重输入,但允许除第一个之外的空框
- javascript - javascript中hypen后的字符串大写
- r - 我应该如何处理多项选择/响应(检查所有应用)数据?
- c++ - 如何从 sql 数据库获取记录到 char 数组或字符串或整数?