我有一个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', [], [])
并成功了,但是它删除了不可接受的重复项。
答案 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"}]
答案 1 :(得分:0)
使用此MongoDB查询获取此结果集
db.collection.aggregate([
{ $unwind : "$books"},
{ $group: {
_id: null,
items:
{ $push: "$books" }
}}
]);