Mongodb 查找与聚合匹配返回一个空数组
Posted
技术标签:
【中文标题】Mongodb 查找与聚合匹配返回一个空数组【英文标题】:Mongodb lookup with match in aggregate returns an empty array 【发布时间】:2020-06-24 13:55:38 【问题描述】:这是我的用户文档
"_id":"02a33b9a-284c-4869-885e-d46981fdd679",
"context":
"email":"someemail@gmail.com",
"firstName":"John",
"lastName":"Smith",
"company":[
"e2467c93-114b-4613-a842-f311a8c537b3"
],
,
和一份公司文件
"_id":"e2467c93-114b-4613-a842-f311a8c537b3",
"context":
"name":"Coca Cola",
"image":"someimage",
,
;
这是我对用户的查询
let users = await Persons.aggregate(
[$project:
name: $concat: ['$context.firstName', ' ', '$context.lastName'],
companyId: $arrayElemAt: ['$context.company', 0]
,
$match: name: searchRegExp,
$lookup: from: 'companies', let: company_id: $arrayElemAt: ['$context.company', 0], pipeline:
[
$match:
$expr:
$eq: ['$_id', '$$company_id']
,
$project: name: '$context.name'
],
as: 'company'
]).toArray()
当我运行这个查询时,我将公司字段作为一个空数组,我在这里做错了什么?
【问题讨论】:
【参考方案1】:您的第一个管道阶段$project
仅输出_id
、name
和companyId
,因此当您尝试在$context.company
中引用$context.company
时将有一个空值。你可以改用$addFields:
$addFields:
name:
$concat: [
"$context.firstName",
" ",
"$context.lastName"
]
,
companyId:
$arrayElemAt: [
"$context.company",
0
]
Mongo Playground
【讨论】:
【参考方案2】:当您添加字段companyId: $arrayElemAt: ['$context.company', 0]
时,您可以使用$lookup
的简单版本。无需设置两次,一次为companyId: ...
,一次为let: company_id: ...
db.user.aggregate([
$addFields:
name: $concat: ["$context.firstName", " ", "$context.lastName"] ,
companyId: $arrayElemAt: ["$context.company", 0]
,
$lookup:
from: "company",
localField: "companyId",
foreignField: "_id",
as: "company"
])
【讨论】:
以上是关于Mongodb 查找与聚合匹配返回一个空数组的主要内容,如果未能解决你的问题,请参考以下文章