MongoDB 在多个相关集合之间查找数据

问题描述 投票:0回答:1

我有 3 个收藏:

users
    db.users.insert({ _id: 1, username: 'mark' });
    db.users.insert({ _id: 2, username: 'leon' });
    db.users.insert({ _id: 3, username: 'leontin'});
providers
    db.providers.insert({ _id: 1, name: 'prov1' });
    db.providers.insert({ _id: 2, name: 'prov2' });
    db.providers.insert({ _id: 3, name: 'prov3' });
    db.providers.insert({ _id: 39, name: 'prov39' });
data
    db.data.insert(
    {
      _id: ObjectId('6675309f82bdfbe3b00febfa'),
      user: 1,
      provider: 1,
      message: '94451 Laos Sweden Iran',
    });
    db.data.insert(
    {
      _id: ObjectId('6675309f82bdfbe3b00febfb'),
      user: 2,
      provider: 3,
      message: 'message  22222',
    });
    db.data.insert( 
    {
      _id: ObjectId('6675309f82bdfbe3b00febfc'),
      user: 3,
      provider: 39,
      message: 'message  3333',
    });

如果我搜索:

db.data.aggregate([{'$lookup' : {"from" :"users", "localField" : "user", "foreignField" : "_id", "as" : "user_info"}}, {'$unwind': "$user_info"}, { $match: { $expr: { $regexMatch: { input: "$user_info.username" , regex: "^leo", options: "i" } } } }]);

运作良好。

** 但我需要添加更多此查询:whereprovider.name like '^prov3' **

我已经添加了相关的收藏,但我无法添加喜欢的

db.data.aggregate([{'$lookup' : {"from" :"users", "localField" : "user", "foreignField" : "_id", "as" : "user_info"}}, {'$unwind': "$user_info"}, {'$lookup' : {"from" :"providers", "localField" : "provider", "foreignField" : "_id", "as" : "provider_info"}}, {'$unwind': "$provider_info"}, { $match: { $expr: { $regexMatch: { input: "$user_info.username" , regex: "^leo", options: "i" } } } }]);

任何帮助,提前致谢。

问候我。

mongodb match lookup expr
1个回答
0
投票

$match
阶段,您应该使用
$and
运算符来根据
user_info.username
provider_info.name
标准匹配文档。

db.data.aggregate([
  {
    "$lookup": {
      "from": "users",
      "localField": "user",
      "foreignField": "_id",
      "as": "user_info"
    }
  },
  {
    "$lookup": {
      "from": "providers",
      "localField": "provider",
      "foreignField": "_id",
      "as": "provider_info"
    }
  },
  {
    $match: {
      $expr: {
        $and: [
          {
            $regexMatch: {
              input: {
                $first: "$user_info.username"
              },
              regex: "^leo",
              options: "i"
            }
          },
          {
            $regexMatch: {
              input: {
                $first: "$provider_info.name"
              },
              regex: "^prov3",
              options: "i"
            }
          }
        ]
      }
    }
  }
])

演示@Mongo Playground

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.