首页 > 解决方案 > 使用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"]

标签: javascriptnode.jsmongodb

解决方案


您可以使用以下聚合

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" }
  }}
])

Mongo游乐场


推荐阅读