在连接字段上具有匹配条件的MongoDB查找

时间:2017-10-26 14:46:48

标签: mongodb mongodb-query aggregation-framework

我是mongoDB的新手,我想做类似下面的事情:

我有两个系列:

Collection_1
-----------------------
Name | MobileNo   | CountryCode
S1   | 9199123456 | 91
S2   | 9199567892 | 91
S3   | 9712345678 | 971
S4   | 9716598984 | 971
S5   | 9188687789 | 91


Collection_2
----------------------
MobileNo | CountryCode
9199     | 91
9716     | 971


I have two queries :
1). I want to select all the documents of collection_1 which MobileNo is start 
    with 9199% or 9716% and CountryCode is same same.
    I want to apply like condition on collection_2 result.
2). Can we use like condition and select Collection_1's documents which start with 9199% and 9716% without CountryCode join (lookup)? 

我尝试过第一次查询并做了类似的事情

db.Collection_1.aggregate([
   {
      $lookup:
         {
            from: "Collection_2",
            localField: "CountryCode",
            foreignField: "CountryCode",
            as: "result"
        }
   },
   {
      $unwind: "$CountryCode"
   },
   {      
      $match: { MobileNo : /$result.MobileNo/ }   
   }
]);

但无法找到任何记录。

任何人都可以帮我降低产量吗?

Output
------------------
Name | MobileNo    | CountryCode
S1   | 9199123456  | 91
S2   | 9199567892  | 91
S4   | 9716598984  | 971

提前致谢。
Hemik Gajjar

2 个答案:

答案 0 :(得分:1)

我找到了解决方案,我们可以对实际值进行子字符串并与查找值进行比较。

答案 1 :(得分:-1)

抱歉,没有测试数据查询

db.Collection_1.find({$or:[{"MobileNo":/^9199/}, {"MobileNo":/^9716/}]});