dousu8767 2019-02-11 14:05
浏览 323
已采纳

Yii2的mongodb集合 - 获取嵌套数组的所有内容

I have a Yii2 mongodb's collection that looks like this:

{
 "_id" : "123",
 "books" : [
  {
   "author" : "John",
   "title" : "The Book"
  },
  {
   "author" : "Smith",
   "title" : "Something!"
  }
 ]
}
{
 "_id" : "321",
 "books" : [
  {
   "author" : "John",
   "title" : "The Book"
  }
 ]
}
...

And I want to get an array of all books (an array of arrays basically):

[
  {
   "author" : "John",
   "title" : "The Book"
  },
  {
   "author" : "Smith",
   "title" : "Something!"
  },
  {
   "author" : "John",
   "title" : "The Book"
  }
...
]

I saw answers to close questions, but they all achieve something a bit different. Also tried $collection->distinct('books', [], []) and it worked, but it removed duplicates which is unacceptable.

  • 写回答

2条回答 默认 最新

  • dongyi2083 2019-02-12 13:32
    关注

    Use this MongoDB query to get this resultset

    db.collection.aggregate([
        { $unwind : "$books"}, 
        { $group: { 
          _id: null, 
          items: 
            { $push: "$books" } 
        }}
    ]);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?