Py学习  »  MongoDB

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

NapoleonTheCake • 5 年前 • 862 次点击  

我有一个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', [], []) 它起作用了,但它删除了不可接受的副本。

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/30805
 
862 次点击  
文章 [ 2 ]  |  最新文章 5 年前
Always Sunny
Reply   •   1 楼
Always Sunny    5 年前

让我们用这种方法 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

Govind
Reply   •   2 楼
Govind    5 年前

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

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