3

I have documents with a field containing an array of values which can be duplicated. I want to transform these documents with an extra field corresponding to unique values of this array. I tried aggregate + addToSet without success.

Data:

{..., "random_integers" : [1, 1, 2, 2, 3, 3]},
{..., "random_integers" : [2, 3, 4, 4, 5, 6]},
{..., "random_integers" : [9, 9, 8, 8, 7, 7]}

Expecting:

{
    ...
    "random_integers" : [1, 1, 2, 2, 3, 3],
    "unique_integers" : [1, 2, 3],
},
{
    ...
    "random_integers" : [2, 3, 4, 4, 5, 6],
    "unique_integers" : [2, 3, 4, 5, 6],

},
{
     ...
    "random_integers" : [9, 9, 8, 8, 7, 7],
    "unique_integers" : [7, 8, 9],
}

Try with aggregate + addToSet():

# Query
db.getCollection().aggregate([
    {
        $group: {
            _id: '$_id',
            unique_integers: {$addToSet: '$random_integers' }
        }
    }
])

# Results
{..., "unique_integers" : [[1, 1, 2, 2, 3, 3]]},
{..., "unique_integers" : [[2, 3, 4, 4, 5, 6]]},
{..., "unique_integers" : [[9, 9, 8, 8, 7, 7]]}

$addToSet add the whole list into a set, instead of each element of the array. I tried to combine $addToSet with $each but it is not recognize by mongo on a group:

# Query
db.getCollection().aggregate([
    {
        $group: {
            _id: '$_id',
            unique_integers: {$addToSet: { $each: '$random_integers' }}
        }
    }
])

# Error
Error: command failed: {
    "ok" : 0,
    "errmsg" : "Unrecognized expression '$each'",
    "code" : 168,
    "codeName" : "InvalidPipelineOperator"
} : aggregate failed 
1
  • You can just do the $setIntersection on the same array field to get the array with unique values (and no need for the $group). Commented Nov 19, 2019 at 3:43

1 Answer 1

7
db.ints.aggregate( [
  { $project: { 
        random_integers: 1,
        unique_integers: { $setIntersection: [ "$random_integers", "$random_integers" ] },  
       _id: 0 
  } }
] )
Sign up to request clarification or add additional context in comments.

1 Comment

This is working with $setIntersection: "$random_integers" too

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.