mongodb - 如何从聚合 mongoDB 中获取结果?
问题描述
我有一个如下集合:
{ "_id" : ObjectId("5716617f4af77ca97a9614bd"), "flag": { "status": true, "userId": ObjectId"606b0e9f00bece43471baa50")}, "text" : "Main Comment 1", "reply" : [ { "_id" : ObjectId("571661cd4af77ca97a9614c1"), "flag": { "status": true }, "text" : "Main Comment 1 reply 1" }, { "_id" : ObjectId("571661cd4af77ca97a9614c2"), "flag": { "status": true, "userId": ObjectId("606b0e9f00bece43471baa48")}, "text" : "Main Comment 1 reply 2" } ] }
预期结果是,
{ "_id" : ObjectId("5716617f4af77ca97a9614bd"), "text" : "Main Comment 1", reply: { } }
{ "_id" : ObjectId("5716617f4af77ca97a9614bd"), "text" : "Main Comment 1", reply: { "_id" : ObjectId("571661cd4af77ca97a9614c2"), "text" : "Main Comment 1 reply 1" } }
{ "_id" : ObjectId("5716617f4af77ca97a9614bd"), "text" : "Main Comment 1", reply: { "_id" : ObjectId("571661cd4af77ca97a9614c2"), "text" : "Main Comment 1 reply 2" } }
这是我正在使用的查询:
db.comments.aggregate([
{ $unwind: { path: "$reply", preserveNullAndEmptyArrays: true } },
{ $match: { $or: [ { 'flag.status': true }, { 'reply.flag.status': true }]} },
])
通过使用此代码,我没有得到预期的结果。请让我知道该怎么做?
解决方案
$match
把你的比赛阶段放在第一位$unwind
解构reply
数组$project
显示必填字段并检查条件reply
是否flag
匹配,reply
否则返回空对象
db.comments.aggregate([
{
$match: {
$or: [
{ "flag.status": true },
{ "reply.flag.status": true }
]
}
},
{
$unwind: {
path: "$reply",
preserveNullAndEmptyArrays: true
}
},
{
$project: {
_id: 1,
text: 1,
reply: {
$cond: [
{ $eq: ["$reply.flag.status", true] },
{
_id: "$reply._id",
text: "$reply.text"
},
{}
]
}
}
}
])
推荐阅读
- azure-table-storage - 如何在 Azure 数据工厂查找中针对表存储添加参数以进行查询
- r - 将电子邮件保存到 R 中的本地文件夹
- java - JDK14 无法运行“java --add-opens”
- clojurescript - 如何在测试套件中包含 cljs.spec 的函数 (Redux)
- spring-boot - 容器化的 spring 应用程序看不到本地文件?
- nginx - 如何在 Ubuntu-18 nginx 中强制更新 SSL 证书
- flask - 如何设置 wtform RadioField 的样式
- python - Python,Pandas:检查列的列表值中的每个元素是否存在于其他数据框中
- angular - 我是否必须将可观察对象明确定义为“有限”?
- python - 有没有办法以 JSON 值传递 Python 命令行