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 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…