正则表达式作为投影中的 $filter [英] regex as $filter in projection

查看:20
本文介绍了正则表达式作为投影中的 $filter的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试查找(使用正则表达式)一个数组字段并仅返回该元素

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

这是我的数据

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

我的查询

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.

我也尝试了 mongodb 聚合,$filter cond 是错误的.我收到错误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);
    }
});

<小时>

根据@zangw 的建议,这是猫鼬版本,但不完整:标签字段很好(需要测试),但查询仍然返回整个文档.

 caseNote
     .aggregate({ $match: {tags: {$in:['area3']}}})
     .unwind('tags')
     .exec(function(err,d){
         res.json(d);
     });

推荐答案

根据这个问题 使用 $regex 作为 $cond 中的表达式,对于当前的 mongo 版本,$regex 不能与 cond 一起使用.

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

也许你可以试试这个,通过$match过滤area3,然后通过$group得到所有匹配的标签,然后去掉_id$project.

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);
    });

结果:

{ "tags" : [ "C area3", "b_area3" ] }

这篇关于正则表达式作为投影中的 $filter的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆