Prakash Kumar Prakash Kumar - 23 days ago 6
Node.js Question

Get back matched array elements present in a document's field which is also an array

I have an array defined below which contains some strings,

arr = ["hola", "hii", "hey", "namaste"];


Now below are the documents i have in mongodb

{
"user_id": "Michael",
"list": ["hola", "ola", "hey", "maybe"]
}


Now i want to write a query in mongodb which returns all "arr" elements which are also present in "list" of the particular "user_id".

So My Desired Output is

_id: "_id" : ObjectId("5828ae4779f2e01b06bb7a61"), results: ["hola", "hey"]


i wrote below query using aggregation but i am getting error as

MongoError: FieldPath field names may not start with '$'


My code

arraymodel.aggregate(
{ $match: { user_id: "Michael" }},
{ $unwind: '$list'},
{ $match: {list: {$in: arr}}},
{ $group: {_id: '$_id', results: {$push: '$list.$'}}},
function(err, docs) {
if (err) {
console.log('Error Finding query results');
console.log(err);
} else {
if (docs) {
console.log('docs: ', docs);
} else {
console.log('No Arr Found');
}
}
}
);

Answer

You can try $setIntersection for this.

db.arrayModel.aggregate(
    [{
        $match: {
            user_id: "Michael"
        }
    }, {
        $project: {
            _id: 1,
            results: {
                $setIntersection: ["$list", ["hola", "hii", "hey", "namaste"]]
            }
        }
    }]
)

Sample Output

{ "_id" : ObjectId("582c6902a5ff9d6d50e722c3"), "results" : [ "hola", "hey" ] }