Hemik Gajjar
Hemik Gajjar

Reputation: 71

MongoDB Lookup with Match condition on join field

I am new in mongoDB and I want to do something like as below :

I have two collections :

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)? 

I have tried for first query and done something like that

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

But unable to found any records.

Can anyone help me to get below output?

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

Thanks in advance.
Hemik Gajjar

Upvotes: 1

Views: 768

Answers (2)

Hemik Gajjar
Hemik Gajjar

Reputation: 71

I found the solution that we can substring the actual value and compare with lookup value.

Upvotes: 2

Sorry, did not test query on the data

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

Upvotes: -1

Related Questions