如何使用MongoDB中的索引"text"搜索多个将对象作为关键字字段值的文档?



我想搜索文档中任何字段中是否存在关键字。一些字段值是对象。因此还需要检查关键字是否出现在该对象中。所以我想到了下面的解决方案。集合:产品(以companyId作为外键),company

mongoQuerydb.products.aggregate([{$match:{$text:{$search:"hello"}}},{$lookup:{from:"companies",localField:"companyId",foreignField:"_id",as:"company"}},{$unwind:"$company"}])

结果'

[
{
_id: ObjectId("63832de4e9dbcd9b2942ded7"),
companyId: [ ObjectId("6383048ae9dbcd9b2942dece") ],
title: 'hello world',
imageUrl: 'https://drive.google.com/file/image',
company: {
_id: ObjectId("6383048ae9dbcd9b2942dece"),
name: 'name1',
url: 'name1.com'
}
}
]

但问题是,我有另一个文档,其中'company.name'具有值"hello"。通过使用上面的查询,它不会返回第二个文档。我怎样才能解决这个问题?

$or你的正确方法是:https://www.mongodb.com/docs/manual/reference/operator/query/or/

.find一起使用如示例links所示,您将得到一个文档数组。

最新更新