Mongodb 搜索多个 collections

Mongodb search multiple collections

基本上我是在搜索消息。 我有 2 collections:

用户:

[
    {
        "_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 的邮件,无论他是发件人还是在某些邮件文本中提到了他.

如何查询这个场景?

你可以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