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

时间:2019-02-11 14:05:58

标签: php mongodb yii2

我有一个Yii2 mongodb的集合,看起来像这样:

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

我想得到所有书籍的数组(基本上是数组):

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

我看到了封闭问题的答案,但它们都取得了一些不同的成就。 还尝试了$collection->distinct('books', [], [])并成功了,但是它删除了不可接受的重复项。

2 个答案:

答案 0 :(得分:0)

让我们使用foreach()这样尝试吗?

<?php
$json = '[{"_id":"123","books":[{"author":"John","title":"The Book"},{"author":"Smith","title":"Something!"}]},{"_id":"321","books":[{"author":"John","title":"The Book"}]}]';

$array = json_decode($json, 1);
$ids = [];
foreach($array as $v) {
    foreach($v['books'] as $book){
        $books[] = $book;
    }
}
echo json_encode($books);
?>

输出:

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

演示: https://3v4l.org/hdJ8H

答案 1 :(得分:0)

使用此MongoDB查询获取此结果集

db.collection.aggregate([
    { $unwind : "$books"}, 
    { $group: { 
      _id: null, 
      items: 
        { $push: "$books" } 
    }}
]);