我正在尝试使用MongoDB Aggregate在2个阵列之间进行操作。
比方说第一个数组是
files = [["1.txt", "2.txt", "4.txt"], [ "1.txt", "2.txt"], [ "1.txt" ]].
另一个是
operators = ["=", "+"]
我该如何编写一个代码,该代码从文件中获取前两个元素,并从运算符中获取一个元素(假设您将“ +”绑定到$ setIntersection,将“ =”绑定到$ setUnion)并执行所需的操作。应当重复此操作,直到没有更多的运算符为止(最后一次使用文件新元素的操作的结果)。在MongoDB中如何使用聚合或其他方法来实现这一点?
我尝试过,我真的尝试过并得到了:
.aggregate([{"$match": {"term":{"$in":["1", "10", "100"]}}},
{"$group": {"_id":"BooleanSearch","files": { "$push": "$docs.d" },"initialSet": { "$first": "$docs.d" }}},
{"$addFields":{"operators":["=", "+"]}},
{"$unwind":"$operators"},
{"$addFields": {"result": {"$reduce": {"input": "$files", "initialValue": "$initialSet" ,"in": {"$switch":{"branches": [
{ case: {"$eq": [ "$operators", "+"]}, then: { "$setIntersection": [ "$$value", "$$this" ]}},
{ case: {"$eq": [ "$operators", "-"]}, then: { "$setDifference": [ "$$value", "$$this" ]}},
{ case: {"$eq": [ "$operators", "="]}, then: { "$setUnion": [ "$$value", "$$this" ]}}],
default: "Index out of bounds"}}}}}},
{"$project":{"_id":0,"result":1}}])
这将产生以下输出:
/* 1 */
{
"result" : [
"1.txt",
"2.txt",
"4.txt"
]
}
/* 2 */
{
"result" : [
"1.txt"
]
}
所有这些操作是:对每个运算符,您都对所有数组进行操作,这不是我想要的,这会为您带来结果(所有数组都具有相同的操作)。如何处理数组的元素而不是整个数组?
所需的结果将是
{ "result" : [ "1.txt" ] }
它是通过文件的前两个元素之间的union(=)获得的,其后是结果与文件的最后一个元素的交集(+)。