我有一个收集资产,这是我的数据
{
"_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
,那么我们应该搜索assests
中的所有installedAt
数组,并返回如下
"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" }
}}
])
MongoPlayground