Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.7k views
in Technique[技术] by (71.8m points)

mongodb - Need a workaround for lookup of a string to objectID foreignField

I'm new to mongodb and currently I'm facing this problem,

db.medical_records.aggregate([
    {
        "$group": {
            "_id": {
                "disease_id": "$disease_id" //a string
            }, "count": { "$sum": 1 }
        }
    },
    {
        "$addFields": {
            "disease_id": { "$toObjectId": "$disease_id" } 
            // i tried to change it into objectID so i could $lookup it
        }
    },
    {
        "$lookup": {
            "from": "diseases", 
            "localField": "disease_id", 
            "foreignField": "_id", 
            "as": "disease"
        }
    }
])

this is an example of my medical record collection

{
    "_id" : ObjectId("5989c8f13f3958120800682e"),
    "disease_id" : "5989c8f13f3958120800682f",
    "patient_id" : "5989c8f13f3958120800681f"
}

disease collection

{
    "_id" : ObjectId("5989c8f13f3958120800682f"),
    "name" : "Culpa autem officia.",
    "code" : "Est aperiam."
}

and the result I expect is kind of,

{
    "_id" : {disease_id: 5989c8f13f3958120800682f},
    "count" : 20,
    "disease" : {
        "_id" : ObjectId("5989c8f13f3958120800682f"),
        "name" : "Culpa autem officia.",
        "code" : "Est aperiam."
    }
}

I need to join my medical record collection to disease collection as queried above.

When I tried to lookup it to disease collection it failed as foreignField is not the same type as the localField. I've been trying for some time to find a workaround on this problem. And the query above returned another error,

Unrecognized expression '$toObjectId'

This problem might have been asked several times, but I really need a workaround on this problem, please help

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

New in 4.0: https://docs.mongodb.com/manual/reference/operator/aggregation/toObjectId/

// Define stage to add convertedId field with converted _id value

idConversionStage = {
   $addFields: {
      convertedId: { $toObjectId: "$_id" }
   }
};

// Define stage to sort documents by the converted qty values

sortStage = {
   $sort: { "convertedId": -1 }
};


db.orders.aggregate( [
   idConversionStage,
   sortStage
])

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...