首页 > 解决方案 > MongoDB搜索多个集合

问题描述

基本上我正在搜索消息。我有 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.jsmongodbsearchmeteor

解决方案


你可以这样

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 是区分大小写的数据库。更新样本


推荐阅读