我正在使用MongoDB,这就是我的文档的样子
{
"_id": 1,
"arr1": ["a", "a", "b", "c"],
"arr2": [1, 4, 2, 3 ],
},
{
"_id": 2,
"arr1": ["z", "a", "b", "a"],
"arr2": [1, 4, 2, 3 ],
}
键arr1
和arr2
中的数组始终具有相同的长度。我想汇总数据,以便根据arr2
过滤掉arr1
中的值。
例如,如果我根据arr1
寻找a
过滤我的收藏品,我希望得到类似的内容:
{ "_id": 1, "arr1": "a", "arr2": 1},
{ "_id": 1, "arr1": "a", "arr2": 4 },
{ "_id": 2, "arr1": "a", "arr2": 3 },
{ "_id": 2, "arr1": "a", "arr2": 3 }
使用MongoDB是否有一些方法可以实现?
谢谢,
Uirá
答案 0 :(得分:1)
试试这个:
db.col1.aggregate([
{ $unwind:
{ path:"$arr2", includeArrayIndex: "i"}},
{ $project:
{
"arr2":1,
"arr1": { $slice: ["$arr1","$i",1] }}
},
{$unwind: "$arr1"}
{$match: { "arr1":"a" }}
])
第一个$ unwind Stage的输出
{ "_id" : 1, "arr1" : [ "a", "a", "b", "c" ], "arr2" : 1, "i" : NumberLong(0) }
{ "_id" : 1, "arr1" : [ "a", "a", "b", "c" ], "arr2" : 4, "i" : NumberLong(1) }
{ "_id" : 1, "arr1" : [ "a", "a", "b", "c" ], "arr2" : 2, "i" : NumberLong(2) }
{ "_id" : 1, "arr1" : [ "a", "a", "b", "c" ], "arr2" : 3, "i" : NumberLong(3) }
{ "_id" : 2, "arr1" : [ "z", "a", "b", "a" ], "arr2" : 1, "i" : NumberLong(0) }
{ "_id" : 2, "arr1" : [ "z", "a", "b", "a" ], "arr2" : 4, "i" : NumberLong(1) }
{ "_id" : 2, "arr1" : [ "z", "a", "b", "a" ], "arr2" : 2, "i" : NumberLong(2) }
{ "_id" : 2, "arr1" : [ "z", "a", "b", "a" ], "arr2" : 3, "i" : NumberLong(3) }
在第二个项目阶段之后输出
{ "_id" : 1, "arr1" : [ "a" ], "arr2" : 1 }
{ "_id" : 1, "arr1" : [ "a" ], "arr2" : 4 }
{ "_id" : 1, "arr1" : [ "b" ], "arr2" : 2 }
{ "_id" : 1, "arr1" : [ "c" ], "arr2" : 3 }
{ "_id" : 2, "arr1" : [ "z" ], "arr2" : 1 }
{ "_id" : 2, "arr1" : [ "a" ], "arr2" : 4 }
{ "_id" : 2, "arr1" : [ "b" ], "arr2" : 2 }
{ "_id" : 2, "arr1" : [ "a" ], "arr2" : 3 }
秒$展开输出
{ "_id" : 1, "arr1" : "a", "arr2" : 1 }
{ "_id" : 1, "arr1" : "a", "arr2" : 4 }
{ "_id" : 1, "arr1" : "b", "arr2" : 2 }
{ "_id" : 1, "arr1" : "c", "arr2" : 3 }
{ "_id" : 2, "arr1" : "z", "arr2" : 1 }
{ "_id" : 2, "arr1" : "a", "arr2" : 4 }
{ "_id" : 2, "arr1" : "b", "arr2" : 2 }
{ "_id" : 2, "arr1" : "a", "arr2" : 3 }
最终$ match输出:
{ "_id" : 1, "arr1" : [ "a" ], "arr2" : 1 }
{ "_id" : 1, "arr1" : [ "a" ], "arr2" : 4 }
{ "_id" : 2, "arr1" : [ "a" ], "arr2" : 4 }
{ "_id" : 2, "arr1" : [ "a" ], "arr2" : 3 }