Search code examples
mongodbmatchaggregate

Mongodb aggregate match value in array


i'm working with the restaurants db in mongo

   {
    "_id" : ObjectId("5c66fcf59e184ea712adfba6"),
    "address" : {
        "building" : "97-22",
        "coord" : [ 
            -73.8601152, 
            40.7311739
        ],
        "street" : "63 Road",
        "zipcode" : "11374"
    },
    "borough" : "Queens",
    "cuisine" : "Jewish/Kosher",
    "grades" : [ 
        {
            "date" : ISODate("2014-11-24T00:00:00.000Z"),
            "grade" : "Z",
            "score" : 20
        }, 
        {
            "date" : ISODate("2013-01-17T00:00:00.000Z"),
            "grade" : "A",
            "score" : 13
        }, 
        {
            "date" : ISODate("2012-08-02T00:00:00.000Z"),
            "grade" : "A",
            "score" : 13
        }, 
        {
            "date" : ISODate("2011-12-15T00:00:00.000Z"),
            "grade" : "B",
            "score" : 25
        }
    ],
    "name" : "Tov Kosher Kitchen",
    "restaurant_id" : "40356068"
    }

I'm tryng to filter with match in aggregate. I want to check if any score in grades is greater than 5

db.runCommand({
aggregate: "restaurants",
pipeline : [
{$match: {"grades": {$anyElementTrue: {"score": {$gt:5}}}}}

but i'm getting this error:

"errmsg" : "unknown operator: $anyElementTrue",

thanks


Solution

  • Try with $elemMatch

    db.restaurants.aggregate([{$match: {"grades": {$elemMatch: {"score": {$gt:5}}}}}])