Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.6k views
in Technique[技术] by (71.8m points)

mongodb - 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);
     });
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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" ] }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...