gpt4 book ai didi

MongoDB - 根据另一个数组过滤一个数组

转载 作者:行者123 更新时间:2023-12-05 05:23:38 24 4
gpt4 key购买 nike

我正在使用 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 ],
}

arr1arr2 中的数组始终具有相同的长度。我想聚合数据,以便我可以根据 arr1 过滤掉 arr2 中的值。

例如,如果我根据 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 来完成?

谢谢,

乌伊拉

最佳答案

试试这个:

db.col1.aggregate([
{ $unwind:
{ path:"$arr2", includeArrayIndex: "i"}},
{ $project:
{
"arr2":1,
"arr1": { $slice: ["$arr1","$i",1] }}
},
{$unwind: "$arr1"}
{$match: { "arr1":"a" }}
])

第一个 $unwind 阶段的输出

{ "_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 }

第二个 $unwind 输出

{ "_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 }

关于MongoDB - 根据另一个数组过滤一个数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37217715/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com