Retrieve only some fields from sub-document

余生颓废 提交于 2019-12-11 06:13:47

问题


(I am an extreme newbie with extremely simple question):

If my database (from the documentation samples) consists of:

{ "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" }

I issue this command:

db.inventory.find( { item: /^j/ }, { size: 1 } )

I get back this document:

{
    "_id" : ObjectId("59448e8544c2d6b6ced4ac66"),
    "size" : {
        "h" : 14.0,
        "w" : 21.0,
        "uom" : "cm"
    }
}

What I want to do is, only get back "h". If I try this command:

db.inventory.find( { item: /^j/ }, { size.h: 1 } )

I get "Unexpected token ."

How can I cause only the "h" field of array "size" to return?

Thanks!

PS, I tried the example and answer in how to retrieve partial objects from object array in a field in mongodb, but the result was "Script executed successfully, but there are no results to show."


回答1:


You have to enclose the key with quotes so it's correct syntax. A key can only contain $, _, and alphanumeric characters. If the key is invalid inside the object literal, just enclose the key with quotes to bypass this:

db.inventory.find( { item: /^j/ }, { 'size.h': 1 } )



回答2:


//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 } 
}]) 
  • You can use Aggregation which can help you to get data in any form .

  • It includes Pipes.

  • It accepts array

Note :- To ignore any property just change 1 to 0 in $project properties

Thanks



来源:https://stackoverflow.com/questions/44600321/retrieve-only-some-fields-from-sub-document

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!