2

I have two arrays as below:

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

I need to find the New Customer Ids which were not in previous year. I tried creating one pipeline in MongoDB Compass but it will give the difference, I am looking for something which can return me elements in ThisMonthCustomerIds but not in LastOneYearCustomerIds. I also tried following other posts on stack overflow but couldn't find a relevant solution.

Expected Result is:

NewCustomerIds:[9,10]

I have tried below Aggregation pipeline which will give me the difference but not new CustomerIds:

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

1 Answer 1

2

The $setDifference operator will work. You have placed the key names in the wrong order.

The array whose elements you want to preserve should come first, followed by the array you want to compare to.

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

The above query will return the output:

{
    "_id" : ObjectId("5f0bfcc55e654d34080a9282"),
    "newCustomerIds" : [
        9,
        10
    ]
}
Sign up to request clarification or add additional context in comments.

1 Comment

Is there a way to do this using $filter, something like $filter: { input: "LastOneYearCustomerIds", cond: $not { $in: ["$$this", "ThisMonthCustomerIds"]}}? I'm trying this alternative but getting a weird syntax error

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.