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
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
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.