mongodb - 对象数组中的 MongoDB 聚合字段
问题描述
我正在尝试解决一个问题一段时间,但不幸的是没有运气。所以我正在重构一些旧代码(它使用众所周知的获取每个文档查询并对其进行循环),并且我正在尝试聚合结果以删除 BE 正在进行的数千次调用。
当前的文档看起来像这样
{
"_id" : ObjectId("5c176fc65f543200019f8d66"),
"category" : "New client",
"description" : "",
"createdById" : ObjectId("5c0a858da9c0f000018382bb"),
"createdAt" : ISODate("2018-12-17T09:43:34.642Z"),
"sentAt" : ISODate("2018-12-17T09:44:25.902Z"),
"scheduleToBeSentAt" : ISODate("2018-01-17T11:43:00.000Z"),
"recipients" : [
{
"user" : ObjectId("5c0a858da9c0f000018382b5"),
"status" : {
"approved" : true,
"lastUpdated" : ISODate("2018-01-17T11:43:00.000Z")
}
},
{
"user" : ObjectId("5c0a858da9c0f000018382b6"),
"status" : {
"approved" : true,
"lastUpdated" : ISODate("2018-01-17T11:43:00.000Z")
}
},
],
"recipientsGroup" : "All",
"isActive" : false,
"notificationSent" : true
}
该字段recipients.user
是Users
集合中用户的 objectID。修改它的正确方法是什么,结果将是
{
"_id": ObjectId("5c176fc65f543200019f8d66"),
"category": "New client",
"description": "",
"createdById": ObjectId("5c0a858da9c0f000018382bb"),
"createdAt": ISODate("2018-12-17T09:43:34.642Z"),
"sentAt": ISODate("2018-12-17T09:44:25.902Z"),
"scheduleToBeSentAt": ISODate("2018-01-17T11:43:00.000Z"),
"recipients": [{
"user": {
"_id": ObjectId("5c0a858da9c0f000018382b5"),
"title": "",
"firstName": "Monique",
"lastName": "Heinrich",
"qualification": "Management",
"isActive": true
},
"status": {
"approved": true,
"lastUpdated": ISODate("2018-01-17T11:43:00.000Z")
}
},
{
"user": {
"_id": ObjectId("5c0a858da9c0f000018382b6"),
"title": "",
"firstName": "Marek",
"lastName": "Pucelik",
"qualification": "Management",
"isActive": true
},
"status": {
"approved": true,
"lastUpdated": ISODate("2018-01-17T11:43:00.000Z")
}
},
],
"recipientsGroup": "All",
"isActive": false,
"notificationSent": true
}
聚合是一个强大的工具,但有时简单的解决方案会让你的大脑受伤......
我尝试过这样的事情,但也没有运气。
db.getCollection('Protocols').aggregate([
{
$lookup: {
from: "Users",
localField: "recipients.user",
foreignField: "_id",
as: "users"
}
},
{
$project: {
"recipients": {
"status": 1,
"user": {
$filter: {
input: "$users",
cond: { $eq: ["$$this._id", "$user"] }
}
},
}
}
}
])
解决方案
您可以$lookup
在聚合管道中使用运算符
https://docs.mongodb.com/manual/reference/operator/aggregation/lookup/
但出于性能原因,您宁愿在recipents
数组中复制用户对象以避免此类复杂查询。
推荐阅读
- android - 为什么在尝试“调用虚拟方法 SearchView.setOnQueryListener”时出现 NullPointerException?
- macos - 安装自制软件时出现错误
- c# - WebDAVClient 显示 NULL 值
- ios - 如何访问不同的嵌套字符串数组swift 5
- laravel - Nginx 1.9.10 & Laravel 8 给出 text/html 的响应;charset=UTF-8 但预期应用程序/json
- python-3.x - 在 Excel 工作表的指定位置插入一列并用 NaN 值填充
- python - 为什么我在更改 instapy like_until 文件时会出错?
- python - 尝试运行 2 个阻塞函数时与 ThreadPoolExecutor 发生死锁
- c++ - 超过一百万的随机素数生成器只给出一半时间的素数
- python-3.x - django 新手,我的终端认为“路径”存在语法错误