正则表达式为投影中的$ filter [英] regex as $filter in projection
问题描述
我试图找到(使用正则表达式)一个数组字段并仅返回该元素
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:无效的运算符$ 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);
});
推荐答案
根据此问题 Use $regex as the expression in a $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
获取所有匹配的标签,然后通过$project
删除_id
.
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屋!