如何在返回的记录中过滤掉不必要的字段(嵌套字段) [英] How to filter out unnecessary fields (nested fields) in returned records

查看:124
本文介绍了如何在返回的记录中过滤掉不必要的字段(嵌套字段)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我怎么只显示年份为20132014

How could I only show the fields table_name and data with year 2013, 2014

记录包含很多字段,

_idtable_nameunit,...,schedule_id

我怎么只显示年份20132014table_namedata字段,我想知道如何使用Pymongo,mongoDB和Mongoid

How could I only show the fields table_name and data with year 2013, 2014, I want to know how to do it with Pymongo, mongoDB, and Mongoid

更具体地说,我希望记录以以下格式返回.

To more specific I want the record returns in the following format.

{
  "_id": "2012-04-25_pce_inflation",
  "table_name": "pce_inflation",
  "unit": "Percent",
  "data": {
    "2012": {
      "number_of_participants": "3"
    },
    "2013": {
      "number_of_participants": "3"
    },
    "2014": {
      "number_of_participants": "7"
    },
    "2015": {
      "number_of_participants": "4"
    }
  },
  "end_date": new Date("2012-04-25T08:00:00+0800"),
  "updated_at": new Date(1426741272196),
  "created_at": new Date(1426741272195),
  "schedule_id": "2012-04-25"
}

预期

{
  "table_name": "pce_inflation",

  "data": {
    "2013": {
      "number_of_participants": "3"
    },
    "2014": {
      "number_of_participants": "7"
    }
  },
}

推荐答案

您需要的称为这是通用的方法,而不是特定于驱动程序的解决方案.

Instead of a driver-specific solution, here is the general approach.

例如,您在mongo shell中的常规查询为:

For example, your normal query in mongo shell as:

db.coll.find({"table_name": "pce_inflation"})

现在您想摆脱_id字段,您的查询将变为:

And you now want to get rid of the _id field, your query will become:

db.coll.find({"table_name": "pce_inflation"}, {"_id":0 , "table_name":1, "data.2013":1, "data.2014":1})

在上面的链接中指定了投影的语法

The syntax of the projection is specified in the above link

< field>:< 1或true>指定要包含的字段.

< field>: <1 or true> Specify the inclusion of a field.

< field>:< 0或false>指定禁止显示该字段.

< field>: <0 or false> Specify the suppression of the field.

这篇关于如何在返回的记录中过滤掉不必要的字段(嵌套字段)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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