MongoDB:限制对字段和数组投影的查询

时间:2015-05-26 14:23:21

标签: mongodb

我有一个包含以下信息的集合

{
  "_id" : 1, 
  "info" : { "createdby" : "xyz" }, 
  "states" : [ 11, 10, 9, 3, 2, 1 ]}
}

我只使用查询

来预测状态
db.jobs.find({},{states:1})

然后我只得到状态(和整个状态值数组)!或者我只能通过

选择该阵列中的一个状态
db.jobs.find({},{states : {$slice : 1} })

然后我只获得一个状态值,但同时也包含文档中的所有其他字段。

有没有办法只选择“states”字段,同时只切片数组的一个元素。当然,我可以排除字段,但我希望有一个解决方案,我可以指定这两个条件。

1 个答案:

答案 0 :(得分:1)

您可以通过两种方式执行此操作:

1>使用mongo projection之类的

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

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

所以您的查询为

db.jobs.find({},{states : {$slice : 1} ,"info":0,"_id":0})

2 - ;使用mongo aggregation作为

的其他方式
db.jobs.aggregate({
    "$unwind": "$states"
  }, {
    "$match": {
      "states": 11
    }
  }, // match states (optional)
  {
    "$group": {
      "_id": "$_id",
      "states": {
        "$first": "$states"
      }
    }
  }, {
    "$project": {
      "_id": 0,
      "states": 1
    }
  })
相关问题