2017-08-08 86 views
0

我是新來的MongoDB和我目前面臨這個問題,需要一個字符串的查找一個解決方法的objectID foreignField

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" 
     } 
    } 
]) 

這是我的醫療記錄收集的例子

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

疾病收集

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

,我希望得到的結果是怎麼樣的,

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

我需要將我的病歷收集加入上述的疾病收集中。

當我試圖查找疾病收集它失敗,因爲foreignField不是localField類型。我一直在嘗試尋找解決這個問題的方法。和上面的查詢返回另一個錯誤,

Unrecognized expression '$toObjectId' 

這個問題可能已經問了好幾次,但我真的需要對這個問題的解決方法,請大家幫忙

+0

您是否可以更新您的問題以包括:(1)來自medical_records集合的樣本文檔; (2)疾病收集的樣本文件; (3)顯示您想要的結果的樣本文件。 – glytching

+0

編輯:經過一些更多的谷歌搜索後,我意識到$ toObjectId是不存在的聚合器,所以這個錯誤是預期的結果。 –

回答

0

這不能與你現有的數據結構來完成。

而且在這裏看到:Mongoose $lookup where localField is a string of an ObjectId in foreignField

在這裏:Is it possible to compare string with ObjectId via $lookup

但是,你爲什麼不你的醫療記錄集合中改變的數據是:

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

鑑於這種格式你可以使用以下查詢得到你想要的結果:

db.medical_records.aggregate([ 
    { 
     "$group": { 
      "_id": { 
       "disease_id": "$disease_id" //a string 
      }, "count": { "$sum": 1 } 
     } 
    }, 
    { 
     "$lookup": { 
      "from": "diseases", 
      "localField": "_id.disease_id", 
      "foreignField": "_id", 
      "as": "disease" 
     } 
    } 
]) 

編輯基於您的意見如下:

在MongoDB中沒有$toObjectId運算符。嘗試searching the documentation,你什麼也找不到!所以沒有辦法在不改變數據的情況下實現你的目標。我不知道你提到的「雄辯的laravel-mongodb」框架,但基於它的文檔,我認爲你的模型可能需要一些調整。你現在如何模擬你的關係?

+0

實際上我正在使用一個框架庫(雄辯laravel-mongodb)保存我的數據,因爲它是。但是,然後對於更復雜的查詢,我不得不使用聚合,我做不了多少。我現在問的是如何正確使用$ toObjectId?如果不是因爲它上面的錯誤可能成爲這種情況的解決方法 –

相關問題