[英]MongoDB: How to find (and return) elements in a multidimensional array?
[英]How to make MongoDB find nested json return as an array?
我有此數據:
{
"_id" : ObjectId("5461e16ee7caf96f8f3584a2"),
"num_marcacao" : "100",
"sexo" : "Fêmea",
"idade" : "20",
"bigdata" : {
"abortos" : [
{
"data_aborto" : "2014-11-11",
"causa_aborto" : "Aborto causa 1"
},
{
"data_aborto" : "2014-09-01",
"causa_aborto" : "Aborto causa 2"
}
],
"crias" : [
ObjectId("5461e16ee7caf96f8f3584a2")
]
}
}
{
"_id" : ObjectId("5461e1cae7caf96f8f3584a4"),
"num_marcacao" : "200",
"sexo" : "Fêmea",
"bigdata" : {
"crias" : [
ObjectId("5461e1f3e7caf96f8f3584a5"),
ObjectId("5461e760e7caf96f8f3584a6")
]
}
}
使用以下獨特的功能,我得到一個結果
db.animal.distinct('_id', {'bigdata.crias':{$exists:true}}
結果:
{
"0" : ObjectId("5461e16ee7caf96f8f3584a2"),
"1" : ObjectId("5461e1cae7caf96f8f3584a4")
}
現在,我想獲取bigdata.crias
的數組,就像非bigdata.crias
查詢的結果一樣。 我正在嘗試這樣做:
db.animal.find(
{
$and: [
{'num_marcacao': '200'},
{'bigdata.crias':{$exists: true}}
]
},
{
'bigdata.crias': true,
'_id': false
}
)
但是結果卻不像我需要的那樣。 這就是返回的內容:
{
"bigdata" : {
"crias" : [
ObjectId("5461e1f3e7caf96f8f3584a5"),
ObjectId("5461e760e7caf96f8f3584a6")
]
}
}
我需要
{
"0" : ObjectId("5461e1f3e7caf96f8f3584a5"),
"1" : ObjectId("5461e760e7caf96f8f3584a6")
}
無論如何。 MongoDB通常不會通過.find()
或.aggregate()
方法或它們周圍的任何常規方法來執行此操作。 只有.distinct()
方法會調用一種特殊形式,其中給出的結果是“真正的”,只是指定的“鍵”的數組不同。
您始終可以“檢查”返回的對象,而只需在結構中使用數組元素。 您還可以首先為.distinct()
命令方法指定一個“查詢”參數:
db.collection.distinct(
"bigdata.crias",
{
"bigdata.crias": { "$exists": true },
"num_marcacao": "200"
}
);
您還會看到$and
參數是多余的。 默認情況下,所有MongoDB查詢參數都是“和”實現。 除非您在同一“字段名稱”上指定“多個”條件,否則您不需要這樣做。 這將破壞基本的“哈希/映射”“唯一鍵”規則,從而導致無效對象,這就是為什么“ array”用於此表單以使其保持有效。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.