【发布时间】:2020-09-20 12:55:15
【问题描述】:
我有一个这样的 MongoDB 聚合查询
[{ "$match" : { "isDeleted" : false } }
, { "$match" : { "$or" : [{ "arrayCol.col_1" : "Yes", "arrayCol.subArrCol.col_2" : 10 }, { "arrayCol.subArrCol.col_3" : 2000 }] } }
, { "$project" : { "_id" : 0, "col_0" : "$col_0", "col_1" : "$arrayCol.col_1", "col_2" : "$arrayCol.subArrCol.col_2", "col_3" : "$arrayCol.subArrCol.col_3" } }]
目前正在返回如下 2 个文档
/* 1 */
{
"col_0" : "xyz",
"col_1" : "Yes",
"col_2" : [
10
],
"col_3" : [
2013,
1995
]
},
/* 2 */
{
"col_0" : "pqr",
"col_1" : "Yes",
"col_2" : [
9,
10
],
"col_3" : [
2000,
2000
]
}
现在我想同时展开“col_2”和“col_3”,但它应该只返回那些像以前一样的文档,即那些 col_2 = 10 或 col_3 = 2000 的文档。
我的预期结果集如下,
/* 1 */
{
"col_0" : "xyz",
"col_1" : "Yes",
"col_2" : 10,
"col_3" : 2013
},
/* 2 */
{
"col_0" : "pqr",
"col_1" : "Yes",
"col_2" : 9,
"col_3" : 2000
}
/* 3 */
{
"col_0" : "pqr",
"col_1" : "Yes",
"col_2" : 10,
"col_3" : 2000
}
如果匹配条件是 AND 子句,那么我可以在展开后再次添加相同的匹配条件以消除错误值。 但是我如何在 OR 子句中解决这个问题/有人可以帮忙吗? 我是 MongoDB 新手。
我收藏的文档如下,
{
"_id": "1234-5f33-4703-be7f-3ea679951af3",
"col_0": "xyz",
"arrayCol": {
"col_1": "Yes",
"subArrCol": [
{
"col_2": 10,
"col_3": 2013
},
{
"col_3": 1995
}
]
}
},
{
"_id": "5678-5f33-4703-be7f-3ea679951af3",
"col_0": "pqr",
"arrayCol": {
"col_1": "Yes",
"subArrCol": [
{
"col_2": 9,
"col_3": 2000
},
{
"col_2": 10,
"col_3": 2000,
"col_4": "abc"
}
]
}
}
【问题讨论】:
-
集合和预期结果集均已添加。为了更清晰,查询也有所改变。请检查
标签: mongodb mongodb-query aggregate