Samuel Rabini
Samuel Rabini

Reputation: 143

Mongo $aggregate and $filter not working

I've a problem while filtering an array of values of a specific document. The collection name is lists and I've a document with 'fields' as _id. Here is a part of document:

{
"_id" : "fields",
"values" : [ 
    {
        "name" : "sku",
        "dt" : "text"
    }, 
    {
        "name" : "title",
        "dt" : "text"
    }, 
    {
        "name" : "desc",
        "dt" : "text"
    }, 
    {
        "name" : "brand",
        "dt" : "text"
    }, 
    {
        "name" : "cur",
        "dt" : "text"
    }, 
    {
        "name" : "l_img",
        "dt" : "text"
    }, 
    .....
    ]
}

I need to retrieve an array of strings that match a specified Regular Expression.

This is my query:

db.lists.aggregate([
{
    $match : { _id: "fields"}
},
{
    $project: {
       values: {
          $filter: {
             input: "$values",
             as: "val",
             cond: { "$$val.name" : { $regex: /sk/i } }
          }
       }
    }
 }
]);

and this is the error I get:

assert: command failed: { "ok" : 0, "errmsg" : "invalid operator '$$val.name'", "code" : 15999 } : aggregate failed

I tried the situation of the post How to filter array in subdocument with MongoDB and it works fine, but implemented for my needs and document structure does not. Where I'm doing wrong??

The oldest syntax (previous 3.2 version) works fine:

db.lists.aggregate(
{ $match: {_id: "fields"}},
{ $unwind: '$values'},
{ $match: {'values.name': { $regex: /sk/i }}},
{ $group: {_id: '$_id', values: {$push: '$values.name'}}})

In fact I get:

{ "_id" : "fields", "values" : [ "sku", "sku_parent", "skin_type", "skin_tone" ] }

My mongo db version is 3.2.9.

Upvotes: 0

Views: 5408

Answers (1)

Samuel Rabini
Samuel Rabini

Reputation: 143

the problem seems not to be the regex:

db.lists.aggregate([
{
   $match : { _id: "fields"}
},
{
   $project: {
      values: {
        $filter: {
           input: "$values",
           as: "val",
           cond: { "$$val.name" : "sku" }
        }
     }
   }
}
]);

assert: command failed: { "ok" : 0, "errmsg" : "invalid operator '$$val.name'", "code" : 15999 } : aggregate failed

Upvotes: 0

Related Questions