假设Mongo Atlas数据库中有两个集合。
- 用户
- 库存
Users
具有name
和userId
Inventory
具有inventoryId
、userId
我想按用户的名称搜索所有库存项目。用户表中可以有多个具有相同名称的条目。有什么有效的方法可以做到这一点,也可以处理这两个集合中的大量文档?
通常,如果您想在两个集合中搜索大量文档,其中文本是筛选条件之一(在本例中为name
(,最好的解决方案通常是查找。
以下是一个从sample_mflix数据集修改的示例,说明您需要在聚合管道中涵盖的步骤:
var db = Products,
joinSearchQuery = db.Users.aggregate([
{
'$search': {
'text': {
'query': 'Ned Stark', // could also be autocomplete to be a nicer feature
'path': 'name'
}
}
}, {
'$lookup': {
'from': 'Inventory',
'localField': 'userId',
'foreignField': 'userId',
'as': 'inventoryFromUser',
'pipeline': [
...
]
}
}
]);
这个查询的有趣之处在于,如果只是一个常规的文本查询,名称搜索方面可能会非常昂贵和糟糕,因为搜索最好使用Atlas搜索。如果有一个交互式搜索表单,使用$search
自动完成也可能很有趣。有一个免费的永久层,所以它不需要花钱,除非它很大。
据我所知,最有效的方法是使用$lookup,但它只在聚合管道的一个阶段可用
mongo.collection('users').aggregate([
...
{$lookup: {
from: "inventory", //name of the collection
localField: "userId", //localField
foreignField: "userId", //foreignField
as: "inventory". //as <=> name in the document
}},
...
]).toArray(),
这种操作通常需要数据操作,因为添加的新字段是一个数组。