繁体   English   中英

如何根据存储在另一个集合中的数据在 MongoDB 集合中搜索文本?

[英]How to search for text in a MongoDB collection based on data stored in another collection?

假设我们在 Mongo Atlas 数据库中有 2 collections。

  • 用户
  • 存货

Usersname和用户userId

InventoryinventoryIduserId

我想按用户名搜索所有库存项目。 用户表中可以有多个具有相同名称的条目。 有什么有效的方法来做到这一点,它还可以处理这2个collections中的很多文件?

据我所知,最有效的方法是使用 $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(),

这种操作通常需要数据操作,因为添加的新字段是一个数组。

一般来说,如果要搜索大量文档,在两个 collections 中,其中 text 是过滤条件之一(在本例中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 来完成搜索。 如果有交互式搜索表单,使用$search的自动完成也可能很有趣。 有一个永远免费的等级,所以除非它很大,否则它不会花钱。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM