(我是一个非常简单问题的极端新手):
如果我的数据库(来自文档样本)包含:
{ "item" : "journal", "qty" : 25, "size" : { "h" : 14, "w" : 21, "uom" : "cm" }, "status" : "A" }
{ "item" : "notebook", "qty" : 50, "size" : { "h" : 8.5, "w" : 11, "uom" : "in" }, "status" : "A" }
{ "item" : "paper", "qty" : 100, "size" : { "h" : 8.5, "w" : 11, "uom" : "in" }, "status" : "D" }
{ "item" : "planner", "qty" : 75, "size" : { "h" : 22.85, "w" : 30, "uom" : "cm" }, "status" : "D" }
{ "item" : "postcard", "qty" : 45, "size" : { "h" : 10, "w" : 15.25, "uom" : "cm" }, "status" : "A" }
我发出这个命令:
db.inventory.find( { item: /^j/ }, { size: 1 } )
我收回这份文件:
{
"_id" : ObjectId("59448e8544c2d6b6ced4ac66"),
"size" : {
"h" : 14.0,
"w" : 21.0,
"uom" : "cm"
}
}
我想做的是,只回到“h”。如果我尝试这个命令:
db.inventory.find( { item: /^j/ }, { size.h: 1 } )
我得到“Unexpected token .
”
如何才能返回数组“size”的“h”字段?
谢谢!
PS,我尝试了示例并在how to retrieve partial objects from object array in a field in mongodb中回答,但结果是“Script executed successfully, but there are no results to show.
”
答案 0 :(得分:2)
你必须用引号括起键,这样它的语法正确。密钥只能包含$,_和字母数字字符。如果对象文字中的键无效,只需用引号括起该键以绕过它:
\[root-of-your-project]\.settings\org.eclipse.wst.common.component
答案 1 :(得分:0)
//use when you want `_id,size` (As object) with its only property `h` in
//$project,
db.inventory.aggregate([{$match:{ item: /^j/ } },{ $project:{
"size.h":"$size.h" } }])
//use when you want `_id,size` size ase whole object
//$project,
db.inventory.aggregate([{$match:{ item: /^j/ } },{ $project:{ "size":1 }
}])
您可以使用聚合来帮助您获取任何形式的数据。
它包括管道。
注意: - 要忽略任何属性,只需在$project
属性中将1更改为0
由于