从mongo集合中的嵌套数组元素中获取特定值

时间:2014-02-21 17:44:28

标签: mongodb mongoid

我有一个包含这样的对象的集合:

{
  "_id": ObjectId("52ed12c144aecc4bf004d0b6"),
  "title": "myBook",
  "summary": "This is a book summary",
  "covers": [
    "http://url.com/cover1.jpg",
    "http://url.com/cover2.jpg",
  ],
  "urls": [
    "http://url.com/myBook",
    "http://url.com/myBook/option2"
  ],
  "genres": [
    "comedy",
    "romantic"
  ],
  "created_at": ISODate("2012-12-17T23:00:00Z"),
  "modify_at": ISODate("2014-02-01T15:41:48.149Z")
}

但我只想从封面网址属性中获取第一个值,我的输出json应该是这样的:

{
  "_id": ObjectId("52ed12c144aecc4bf004d0b6"),
  "title": "myBook",
  "summary": "This is a book summary",
  "covers": "http://url.com/cover1.jpg",
  "urls": "http://url.com/myBook"
  "genres": [
    "comedy",
    "romantic"
  ],
  "created_at": ISODate("2012-12-17T23:00:00Z"),
  "modify_at": ISODate("2014-02-01T15:41:48.149Z")
}

我想我必须使用map_reduce,但我不确定我应该如何查询,我试过了:

db.books.mapReduce( function(){ emit(this._id, this.covers); }, function(key, values){ return values[0]; }, { out: "map_reduce_covers" } )

但这似乎不起作用。

1 个答案:

答案 0 :(得分:0)

您可以使用$slice投影运算符来控制输出中包含数组的哪些元素。

 
db.books.findOne({}, {covers: {$slice: 1}, urls: {$slice: 1}})

输出:

{
  "_id": ObjectId("52ed12c144aecc4bf004d0b6"),
  "title": "myBook",
  "summary": "This is a book summary",
  "covers": [
    "http://url.com/cover1.jpg"
  ],
  "urls": [
    "http://url.com/myBook"
  ],
  "genres": [
    "comedy",
    "romantic"
  ],
  "created_at": ISODate("2012-12-17T17:00:00-0600"),
  "modify_at": ISODate("2014-02-01T09:41:48.149-0600")
}

coversurls仍然是数组,如果您想要更改它,它会变得更复杂。