0

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');
                }
            }
        }
        );
Prakash Kumar
  • 829
  • 1
  • 15
  • 32

2 Answers2

2

simply get rid of the $ in {$push: '$list.$'} and you will get the desired output.

below is the complete query :

    db.collection.aggregate(
{$match:{user_id:"Michael"}},
{$unwind:'$list'},
{$match:{list:{$in:["hola","hey"]}}},
{$group:{_id:"$_id",results:{$push:"$list"}}})
satish chennupati
  • 2,602
  • 1
  • 18
  • 27
1

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" ] }
s7vr
  • 73,656
  • 11
  • 106
  • 127