仅检索子文档中的某些字段 [英] Retrieve only some fields from sub-document

查看:96
本文介绍了仅检索子文档中的某些字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

(我是一个极端的新手,有一个非常简单的问题):

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

我发出以下命令:

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

我找回这份文件:

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

我想做的是,只取回"h".如果我尝试执行以下命令:

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

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

我得到"Unexpected token ."

如何仅使数组"size"的"h"字段返回?

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

谢谢!

PS,我尝试了示例并在Script executed successfully, but there are no results to show."

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."

推荐答案

您必须将键括在引号中,以便使用正确的语法.键只能包含$,_和字母数字字符.如果键在对象文字内部无效,则只需用引号将键括起来即可绕过此操作:

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

这篇关于仅检索子文档中的某些字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆