2

I have the following document:

{
  userId: 1234,
  contacts: ['a', 'b', 'c', 'd'],
  conversations: ['a', 'b', 'e'],
}

I want to get distinct value from the contacts and conversations array. So for this case, the output should be: a, b, c, d, e

1 Answer 1

2

Use $setUnion operator to aggregate values from two arrays:

db.test.aggregate([
    {
        $project: {
            userId: 1, 
            values: {
                $setUnion: [
                    '$contacts',
                    '$conversations'
                ]
            }
        }
    }
])

Result:

{ "userId" : 1234, "values" : [ "a", "b", "c", "d", "e" ] }

UPDATE: For MongoDB 2.4 you can map each document on client side. Define unique function for array. And then simply map each document

db.test.find().map(function(doc) {
   return { 
      userId : doc.userId, 
      values : doc.contacts.concat(doc.conversations).unique()
   };
})

Note: if there is several documents with same userId you can group them on server side.

Sign up to request clarification or add additional context in comments.

1 Comment

setUnion seems to be new in 2.6. I'm using 2.4. Any other way?

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.