鑒于集合中名為“blah”的以下檔案資料...
[
{
"_id" : ObjectId("60913f55987438922d5f0db6"),
"procedureCode" : "code1",
"description" : "Description 1",
"coding" : [
{
"system" : "ABC",
"code" : "L111"
},
{
"system" : "DEFG",
"code" : "S222"
}
]
},
{
"_id" : ObjectId("60913f55987438922d5f0dbc"),
"procedureCode" : "code2",
"description" : "Description 2",
"coding" : [
{
"system" : "ABC",
"code" : "L999"
},
{
"system" : "DEFG",
"code" : "X3333"
}
]
}
]
我想要得到的是所有父母的所有編碼元素system,ABC以及類似的陣列codes。
[
{ "code": "L111" },
{ "code": "L999" },
]
如果我使用db.getCollection('blah').find({"coding.system": "ABC"}),我會coding在ICD.
如果我用...
db.getCollection("blah")
.find({ "coding.system": "ABC" })
.projection({ "coding.code": 1 })
我確實得到了具有“ABC”系統的孩子的父檔案,但是“DEFG”的編碼似乎也隨之而來。
{
"_id" : ObjectId("60913f55987438922d5f0db6"),
"coding" : [
{
"code" : "L989"
},
{
"code" : "S102"
}
]
},
{
"_id" : ObjectId("60913f55987438922d5f0dbc"),
"coding" : [
{
"code" : "L989"
},
{
"code" : "X382"
}
]
}
我也嘗試過:
db.getCollection("blah").aggregate(
{ $unwind: "$coding" },
{ $match: { "system": "ICD" } }
);
..根據此頁面:mongoDB查詢以在嵌套陣列中查找檔案 ...但是使用這種方法無法快速進行。即根本沒有記錄。
請問我需要什么查詢來實作這樣的目標..?
[
{ "code": "L111" },
{ "code": "L999" },
...
]
甚至更好,這個..?
[
"L111",
"L999",
...
]
uj5u.com熱心網友回復:
db.collection.aggregate([
{
$match: { "coding.system": "ABC" }
},
{
$unwind: "$coding"
},
{
$match: { "coding.system": "ABC" }
},
{
$project: { code: "$coding.code" }
}
])
mongoplayground
db.collection.aggregate([
{
$match: { "coding.system": "ABC" }
},
{
$unwind: "$coding"
},
{
$match: { "coding.system": "ABC" }
},
{
$group: {
_id: null,
coding: { $push: "$coding.code" }
}
}
])
mongoplayground
uj5u.com熱心網友回復:
代替$unwind,$match您還可以使用$filter:
db.collection.aggregate([
{ $match: { "coding.system": "ABC" } },
{
$project: {
coding: {
$filter: {
input: "$coding",
cond: { $eq: [ "$$this.system", "ABC" ] }
}
}
}
}
])
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/444037.html
