繁体   English   中英

如何在 MongoDB 聚合管道中获取不在另一个数组中的数组元素?

[英]How to get elements of an array which is not in another array in MongoDB Aggregation Pipeline?

我有两个 arrays 如下:

LastOneYearCustomerIds:[1,2,3,4,5,6,7,8]
ThisMonthCustomerIds:[1,2,3,4,9,10]

我需要找到前一年没有的新客户 ID。 我尝试在 MongoDB Compass 中创建一个管道,但它会有所不同,我正在寻找可以在 ThisMonthCustomerIds 中返回我元素但不能在 LastOneYearCustomerIds 中返回的东西。 我还尝试关注有关堆栈溢出的其他帖子,但找不到相关的解决方案。

预期结果是:

NewCustomerIds:[9,10]

我在聚合管道下面尝试过,这会给我带来差异,但不是新的 CustomerIds:

$project: {
  newCustomerIds:{
    $setDifference:
    ['$LastOneYearCustomerIds','$ThisMonthCustomerIds'
  ]}
}

$setDifference运算符将起作用。 您以错误的顺序放置了键名。

您要保留其元素的数组应该放在第一位,然后是您要比较的数组。

db.test10.aggregate([
    {
        "$project": {
            "newCustomerIds": {
                "$setDifference": ["$ThisMonthCustomerIds", "$LastOneYearCustomerIds"]
            }
        }
    }
])

上述查询将返回 output:

{
    "_id" : ObjectId("5f0bfcc55e654d34080a9282"),
    "newCustomerIds" : [
        9,
        10
    ]
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM