Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

regex as $filter in projection

I'm trying to find (using a regexp) an array field and returns that element only

This is my data

  [
 {
"_id": "56d6e8bbf7404bd80a017edb",
"name": "document1",
"tags": [
  "A area1",
  "B area2",
  "C area3"
]
},
{
"_id": "56d6e8bbf7404bd82d017ede",
"name": "document2",
"tags": [
  "b_area3",
  "b_area4",
  "b_area5"
  ]
}
]

My query

var query=new RegExp('^'+string, "i");

Model.find({tags:query},{'tags.$': 1}, function(err,data){
        if(err) console.log(err);
        res.json(data);
    });

This query selects only the tags field (as I want), but selects the first element. I need the element(s) that matches the query.

EDIT: I tried the mongodb aggregate too, the $filter cond is wrong. I get the error "MongoError: invalid operator $regex"

caseNote.aggregate([
    { $match: {tags:query}},
    { $project: {
        tags: {$filter: {
            input: 'tags',
            as: 'item',
            cond: {$regex: ['$$item', query]}
        }}
    }}
], function (err, result) {
    if (err) {
        console.log(err);
    } else {
        res.json(result);
    }
});

EDIT2: on @zangw suggestion, this is the mongoose version, but it's incomplete: the tags fields is fine (needs test), but the query still returns the whole document.

 caseNote
     .aggregate({ $match: {tags: {$in:['area3']}}})
     .unwind('tags')
     .exec(function(err,d){
         res.json(d);
     });
like image 946
alfredopacino Avatar asked Mar 02 '16 15:03

alfredopacino


People also ask

Can we use regex in MongoDB?

MongoDB uses Perl compatible regular expressions (i.e. "PCRE" ) version 8.42 with UTF-8 support. For restrictions on particular syntax use, see $regex vs. /pattern/ Syntax. The following <options> are available for use with regular expression.


1 Answers

According this issue Use $regex as the expression in a $cond, the $regex could NOT be used with cond for current mongo version.

Maybe you can try this one, filter the area3 through $match, then get all matched tags through $group, then remove the _id through $project.

caseNote.aggregate([{$unwind: '$tags'},
               {$match: {tags: /area3/}},
               {$group: {_id: null, tags: {$push: '$tags'}}},
               {$project: {tags: 1, _id: 0}}])
    .exec(function(err, tags) {
        if (err)
            console.log(err);
        else
            console.log(tags);
    });

Results:

{ "tags" : [ "C area3", "b_area3" ] }
like image 145
zangw Avatar answered Oct 05 '22 07:10

zangw