javascript - 使用NodeJS在数组中搜索关键字,只获取MongoDB中匹配的元素
问题描述
我有一个收藏资产,这是我的数据
{
"_id" : ObjectId("5e71d235a3b5401685a058"),
"company" : ObjectId("5e6b834b5991d70945840"),
"asset_name" : "LG-OLED-55-Inch",
"installedAt" : ["lobby", "storeroom", "f105"],
}
{
"_id" : ObjectId("5e71d235a3b540168475d8"),
"company" : ObjectId("5e6b834b5991d70945840"),
"asset_name" : "LG-OLED-32-Inch",
"installedAt" : ["lobby", "f108"],
}
{
"_id" : ObjectId("5eb3d53a7e16dc70244d6578"),
"company" : ObjectId("5e6b834b5991d70945840"),
"asset_name" : "LG-OLED-68-Inch",
"installedAt" : ["tvroom", "f105"],
}
{
"_id" : ObjectId("5eb3d53a7e16dc7024474a12"),
"company" : ObjectId("5e6b834b5991d70945840"),
"asset_name" : "LG-OLED-22-Inch",
"installedAt" : ["tvroom"],
}
所以对于上述数据,我的要求是搜索关键字installedAt
并返回与用户提供的关键字匹配的所有元素。
例如,如果用户搜索,f10
那么我们应该搜索所有installedAt
数组assests
并返回如下
"installedAt": ["f105","f108"]
我已经尝试使用$in
来获取类似的元素,但它没有像我预期的那样工作。这是我的查询
var autoRecords =[];
key = [searchString];
key.forEach(function(opt){
autoRecords.push(new RegExp(opt,"i"));
});
Assets.find({ "installedAt" : {"$in" : autoRecords},"company": companyId},{"installedAt" : 1})
因此,对于上述查询,当我尝试发送搜索文本时,f10
结果如下
[
{"installedAt":["lobby", "storeroom", "f105"],"_id":"5e71d235a3b5401685a058"},
{"installedAt":["lobby", "f108"],"_id":"5e71d235a3b540168475d8"},
{"installedAt":["tvroom", "f105"],"_id":"5eb3d53a7e16dc70244d6578"},
]
installedAt
即使找到一个,它也会获取数组中的所有元素。所以任何人都可以帮助我只获取数组中匹配的元素并尝试获取这种格式
"installedAt": ["f105","f108"]
解决方案
您可以使用以下聚合
const data = await Assets.aggregate([
{ $match: { installedAt: { $regex: "f10", $options: "i" }}},
{ $unwind: "$installedAt" },
{ $match: { installedAt: { $regex: "f10", $options: "i" }}},
{ $group: {
_id: null,
data: { $addToSet: "$installedAt" }
}}
])
推荐阅读
- vue.js - Vuetify - 限制滑块可以在 v-slider 中移动到的最小值
- java - 在数组中查找以特定数字开头的数字
- java - 如何从可运行的可调用对象中获取类名
- azure-iot-edge - Azure IoT Edge - 模块下载的离线行为
- ios - 设置值 Firebase 时重复子节点
- android - 使用 Room DataSource.Factory 的 Kotlin 协程挂起错误
- android - 不同的 .tflite 文件和 .txt 文件用于在 App 中实现 tensorflow
- jquery - jquery - 如何在同一行的另一列中输入数据后将数据插入最近的 td(单击按钮动态创建表行)
- javascript - 如何从 react-date-picker 中删除此返回日期中的所有额外数字?
- java - 是否可以在处理中返回“text()”?