如何过滤掉返回记录中不需要的字段(嵌套字段)

How to filter out unnecessary fields (nested fields) in returned records

如何只显示 table_namedata 字段 2013, 2014

记录包含很多字段,

_id, table_name, unit, ..., schedule_id

我怎么能只显示 table_namedata 字段 2013, 2014, 我想知道如何用 Pymongo 做到这一点, mongoDB,和 Mongoid

更具体地说,我想要以下格式的记录 returns。

原创

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

你需要的是projection

这里不是特定于驱动程序的解决方案,而是通用方法。

比如你在mongoshell中的正常查询为:

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

而您现在想要删除 _id 字段,您的查询将变为:

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

上面指定了投影的语法link

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

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