U kunt hiervoor een aggregatieraamwerk gebruiken. Gezien de volgende gegevens
> db.post.find()
{ "_id" : 1, "tags" : [ "tag1" ] }
{ "_id" : 2, "tags" : [ "tag1", "tag3" ] }
{ "_id" : 3, "tags" : [ "tag2", "tag4" ] }
{ "_id" : 4, "tags" : [ "tag1", "tag2", "tag3", "tag4" ] }
de aggregatiequery
db.post.aggregate({
$project: {
_id: 1,
tags: 1,
killFlag: {
$const: [true, false]
}
}
}, {
$unwind: "$tags"
}, {
$unwind: "$killFlag"
}, {
$match: {
$nor: [{
tags: {
$in: ['tag1', 'tag2', 'tag4']
},
killFlag: true
}
]
}
}, {
$group: {
_id: "$_id",
tags: {
$addToSet: "$tags"
},
killFlag: {
$max: "$killFlag"
}
}
}, {
$match: {
killFlag: false
}
}, {
$project: {
_id: 1,
tags: 1
}
})
zou je geven
{
"result": [{
"_id": 3,
"tags": [
"tag4",
"tag2"
]
}, {
"_id": 1,
"tags": [
"tag1"
]
}
],
"ok": 1
}