搜索栏的mongodb数组查询

问题描述 投票:1回答:1

我试图返回至少有一个元素从所选字段数组中匹配查询数组的文档。

我尝试了以下查询。

const match_equipment = await studios.find({equipment: {$eleMatch:{$in: ["mic","amp"]}}});
const match_equipment = await studios.find({equipment: {$all: ["mic","amp"]}});

第一个查询给了我 "db查询失败的错误 "第二个查询给了我 "没有找到结果"。

示例文档。

{
    "_id": {"$oid": "5ec5d38be97c8869bee29e78"},
    "equipment": ["guitar", " mic", " amp"],
    "studio_name": "Best recordings",
    "email": "[email protected]",
    "address": "34 harming st. Brunswick",
    "postcode": "3056",
    "price": "50",
    "__v": {"$numberInt": "0"},
    "unavalibility": [
        {
            "times": [{"$numberInt": "13"}],
            "_id": {"$oid": "5ec610e47cf2fb4e84ba0c54"}, "date": {"$date": {"$numberLong": "1591920000000"}}
        }
    ]
}
javascript jquery node.js mongodb searchbar
1个回答
0
投票

你已经很接近了,只是出现了一个语法错误。

它是 $elemMatch 而不是 eleMatch

所以改变它就可以了。

const match_equipment = await studios.find({equipment: {$elemMatch:{$in: ["mic","amp"]}}});

但其本质是 $elemMatch 是比较专业的查询。在你的情况下是不需要的。所以你可以只使用下面的版本,利用的是 $in 只是。

const match_equipment = await studios.find({equipment: {$in: ["mic","amp"]}});
© www.soinside.com 2019 - 2024. All rights reserved.