Rahul Anand
Rahul Anand

Reputation: 573

Select Key from MongoDB key value pair

I am trying to perform lookup on MongoDb between two collections where one of the fields as attribute as an key-value pair where i have to choose only key as my local field parameter.

Sample Json:

key of the below json

{    "distributions" : {
        "5cf88" : "5d023d4aa", 
        "5cfaca42e" : "5d0093a", 
        "5d023d490d" : "5d22abc69093a"
    }
}

_id field of the below json:

{ 
    "_id" : "5d22abc69093a", 
    "activatedBy" : {
        "id" : "5bc53813055aec", 
        "name" : "Test1", 
        "roles" : [
            "root"
        ]
    }
}

Lookup query:

$lookup: {
        from: 'collecection1',
        localField: 'distributions.key',
        foreignField: '_id',
        as: 'Join'
    }

How to get they key form distributions to use for lookup as i need only key of as my join parameter?

Upvotes: 0

Views: 744

Answers (1)

prasad_
prasad_

Reputation: 14287

How to get they key form distributions to use for lookup as i need only key of as my join parameter?

This aggregation query can do that using the $objectToArray aggregation operator:

db.collection1.aggregate( [
 { $addFields: { fieldNameValues: { $objectToArray: "$$ROOT" } } },
 { $unwind: "$fieldNameValues" },
 { $match: { $expr: { $eq: [ { $type: "$fieldNameValues.v" } , "object" ] } } },
 { $addFields: { objs: { $objectToArray: "$fieldNameValues.v" } } },
 { $unwind: "$objs" },
 { $project: { distributions: "$objs"  } },
 { $lookup: {
        from: 'collection2',
        localField: 'distributions.v',
        foreignField: '_id',
        as: 'Join'
   }
 }
] )


where:

collection1:

{ "distributions" : {
        "5cf88" : "5d023d4aa", 
        "5cfaca42e" : "5d0093a", 
        "5d023d490d" : "5d22abc69093a"
    }
}

collection2:

{ 
    "_id" : "5d22abc69093a", 
    "activatedBy" : {
        "id" : "5bc53813055aec", 
        "name" : "Test1", 
        "roles" : [
            "root"
        ]
    }
}

Upvotes: 1

Related Questions