英文:
Mongoose - Search an array and return the matched results
问题
我正在寻找一种方法来返回Mongo(mongoose)中数组中匹配项的方法。
数据结构如下所示:
[
{
"_id": {
"$oid": "123456"
},
"make": "Lamborghini",
"makeLogo": "/images/makeLogos/lamborghini.png",
"models": [
{
"model": "Aventador",
"_id": {
"$oid": "678909t"
}
},
{
"model": "Countach",
"_id": {
"$oid": "678909"
}
}
],
"__v": 0
},
{
"_id": {
"$oid": "2345678i90"
},
"make": "Nissan",
"makeLogo": "/images/makeLogos/nissan.png",
"models": [
{
"model": "350z",
"_id": {
"$oid": "678909gggg"
}
},
{
"model": "370z",
"_id": {
"$oid": "678909rrrrr"
}
}
],
"__v": 0
}
]
我想要搜索:3,并且它应该返回给我350z和370z。
我尝试了以下代码:
modelsModel.find(
{"models.model": { $regex: req.query.carModel + '.*', $options:'i'}}
)
.exec(function(err, models) {
if(err){
res.status(400).json({error: err});
} else {
res.status(200).json({cars: models});
}
});
返回的数据如下所示:
[
{
_id: 5ca893b7587ab519613b806e,
make: 'Lamborghini',
makeLogo: '/images/makeLogos/lamborghini.png',
__v: 0,
models: [
[Object], [Object]
]
}
]
这是当我搜索Countach时返回的,它有一个匹配项。
我知道我在这里显然做错了些什么,但这对我来说是如此新的东西,我甚至不知道从何开始。
提前感谢您!
英文:
I am looking for a way to return matched items under an array in Mongo (mongoose).
The data structure is like this:
[
{
"_id": {
"$oid": "123456"
},
"make": "Lamborghini",
"makeLogo": "/images/makeLogos/lamborghini.png",
"models": [
{
"model": "Aventador",
"_id": {
"$oid": "678909t"
}
},
{
"model": "Countach",
"_id": {
"$oid": "678909"
}
}
],
"__v": 0
},
{
"_id": {
"$oid": "2345678i90"
},
"make": "Nissan",
"makeLogo": "/images/makeLogos/nissan.png",
"models": [
{
"model": "350z",
"_id": {
"$oid": "678909gggg"
}
},
{
"model": "370z",
"_id": {
"$oid": "678909rrrrr"
}
}
],
"__v": 0
}
]
I would like to search: 3 and it should return 350z and 370z to me.
I tried the below:
modelsModel.find(
{"models.model": { $regex: req.query.carModel + '.*', $options:'i'}},
)
.exec(function(err, models) {
if(err){
res.status(400).json({error: err});
} else {
res.status(200).json({cars: models});
}
});
Where the data returned is this:
[
{ _id: 5ca893b7587ab519613b806e,
make: 'Lamborghini',
makeLogo: '/images/makeLogos/lamborghini.png',
__v: 0,
models: [
[Object], [Object]
]
}
]
This is when I searched for Countach which has a match.
I know I am doing something very obviously wrong here but this is so new to me I don't even know where to begin.
Thanks in advance!
答案1
得分: 1
你可以在MongoDB 4.2中使用以下聚合:
db.collection.aggregate([
{ "$match": {
"models.model": { "$regex": "A" }
}},
{ "$project": {
"models": {
"$filter": {
"input": "$models",
"cond": {
"$regexMatch": {
"input": "$$this.model",
"regex": "A"
}
}
}
}
}}
])
英文:
You can use below aggregation with mongodb 4.2
db.collection.aggregate([
{ "$match": {
"models.model": { "$regex": "A" }
}},
{ "$project": {
"models": {
"$filter": {
"input": "$models",
"cond": {
"$regexMatch": {
"input": "$$this.model",
"regex": "A"
}
}
}
}
}}
])
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论