【问题标题】:Mongodb search multiple collectionsMongoDB搜索多个集合
【发布时间】:2021-04-17 10:48:20
【问题描述】:

基本上我正在搜索消息。 我有 2 个收藏:

  • 用户
  • 消息

用户:

[
    {
        "_id": "Xuibgsadbgsi35Gsdf",
        "fullName": "User A"
    },
    {
        "_id": "Afstg34tg4536gh",
        "fullName": "User B"
    },
    {
        "_id": "KHJDFhfs7dfgsvdfwsef",
        "fullName": "User C"
    }
]

消息:

[
    {
        "_id": "YONgsa793423bD",
        "groupId": "Phsdfyg92345sgb7651",
        "senderId": "Xuibgsadbgsi35Gsdf",
        "message": "Hello there!"
    },
    {
        "_id": "sdgDFGbaofh135df",
        "groupId": "Phsdfyg92345sgb7651",
        "senderId": "KHJDFhfs7dfgsvdfwsef",
        "message": "Hello @Xuibgsadbgsi35Gsdf"
    },
    {
        "_id": "sdgDFGbaofh135df",
        "groupId": "Phsdfyg92345sgb7651",
        "senderId": "KHJDFhfs7dfgsvdfwsef",
        "message": "Hello"
    }
]

现在我想在这里搜索:User A,所以我应该得到那些以任何方式涉及User A 的消息,无论是他是发件人还是在某些消息文本中被提及。

如何查询这个场景?

【问题讨论】:

  • 您想在流星的哪个位置执行此操作?在出版物中还是在方法调用中?如果是后者,那么您可以简单地将其分解为两个单独的查询。同样的方法也适用于复杂性稍高的出版物。

标签: node.js mongodb search meteor


【解决方案1】:

你可以this

db.users.aggregate([
  {
    $match: {
      fullName: "User A" 
     } 
  }, 
  {
    "$lookup": {
      "from": "messages",
      let: {
        id: "$_id" //This is what you need to match in the messages collection, kind of variable
      },
      "pipeline": [
        {
          $match: {
            $or: [
              {
                $expr: { //Matching in sender id
                  $eq: [
                    "$senderId",
                    "$$id"
                  ]
                }
              },
              {
                $expr: {
                  "$regexMatch": { //matching in messages
                    "input": "$message",
                    "regex": "$$id",
                    
                  }
                }
              }
            ]
          }
        }
      ],
      "as": "senders"
    }
  },
  {
    $match: {
      $expr: {
        "$gt": [//Filtering only the matched results
          {
            "$size": "$senders"
          },
          0
        ]
      }
    }
  }
])

要添加过滤,您可以在查找之前添加match 阶段,如下所示

{
  $match: {
    fullName: "User A" 
  } 
} 

注意,mongo 是区分大小写的数据库。更新sample

【讨论】:

  • 如果用户存储在 SSO 上的不同远程服务器上怎么办?
  • 您可以将数据存储在集群或单个服务器中。您需要在 mongo 中收集用户。
  • 此解决方案似乎不起作用,我也无法在查询中看到搜索条件
  • 我已经提到了有问题的搜索条件:“现在我想在这里搜索:用户 A,所以我应该得到用户 A 以任何方式参与的那些消息,无论他是发件人还是他在一些消息文本中被提及。”
  • 您能否也更新您的原始答案,以便任何人都可以轻松获得帮助。谢谢
猜你喜欢
  • 2014-07-31
  • 2013-12-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多