I have the following MongoDB document:
{
_id: ObjectId(5),
items: [1,2,3,45,4,67,9,4]
}
I need to fetch that document with filtered items (1, 9, 4)
result:
{
_id: ObjectId(5),
items: [1,9,4]
}
I've tried an $elemMatch projection but it returns only one item:
A.findById(ObjectId(5))
.select({ items: { $elemMatch: {$in: [1, 9, 4]}}})
.exec(function (err, docs) {
console.log(doc); // { _id: ObjectId(5), items: [ 1 ] }
done(err);
});
How can I get the document with items: 1, 9, 4 only?
A.items = A.items.filter( function(i) {return i == 1 || i == 9 || i == 4} );
If you want the document manipulation to happen on the server side, you can use the new Aggregation Framework in MongoDB 2.2:
db.items.aggregate(
// Match the document(s) of interest
{ $match : {
_id: ObjectId("506278b11e41259587e946b2")
}},
// Separate the items array into a stream of documents
{ $unwind : "$items" },
// Filter the array
{ $match : {
items: { $in: [1, 9, 4] }
}},
// Group the results back into a result document
{ $group : {
_id: "$_id",
items: { $addToSet : "$items" }
}}
)
Result:
{
"result" : [
{
"_id" : ObjectId("506278b11e41259587e946b2"),
"items" : [
9,
4,
1
]
}
],
"ok" : 1
}
Use underscore in your node.js app:
npm install underscore
var _ = require('underscore');
You can use the intersection function of arrays:
intersection_.intersection(*arrays)
Computes the list of values that are the intersection of all the arrays. Each value in the result is present in each of the arrays.
_.intersection([1, 2, 3], [101, 2, 1, 10], [2, 1]);
=> [1, 2]