使用 MongoDB 将多个数组聚合到一个大数组中?
要通过 MongoDB 将多个数组聚合到单个数组中,请使用 $project。我们创建一个集合,其中包含文档 -
> db.demo119.insertOne(
... {
... "_id": 101,
... "WebDetails": [
... {
... "ImagePath": "/all/image1",
... "isCorrect": "false"
... },
... {
... "ImagePath": "/all/image2",
... "isCorrect": "true"
... }
... ],
... "ClientDetails": [
... {
... "Name": "Chris",
... "isCorrect": "false"
... },
... {
... "Name": "David",
... "isCorrect": "true"
... }
... ]
... }
... );
{ "acknowledged" : true, "insertedId" : 101 }在集合中使用 find() 方法显示所有文档 -
> db.demo119.find();
这将产生以下输出 -
{
"_id" : 101, "WebDetails" : [
{ "ImagePath" : "/all/image1", "isCorrect" : "false" },
{ "ImagePath" : "/all/image2", "isCorrect" : "true" } ], "ClientDetails" : [
{ "Name" : "Chris", "isCorrect" : "false" }, { "Name" : "David", "isCorrect" : "true" }
]
}以下是使用 MongoDB 将多个数组聚合到单个数组中的查询 -
>
> db.demo119.aggregate([
... { "$project": {
... "AllDetails": {
... "$filter": {
... "input": {
... "$setUnion": [
... { "$ifNull": [ "$WebDetails", [] ] },
... { "$ifNull": [ "$ClientDetails", [] ] }
... ]
... },
... "as": "out",
... "cond": { "$eq": [ "$$out.isCorrect", "false" ] }
... }
... }
... }},
... { "$match": { "AllDetails.0": { "$exists": true } } }
... ])这将产生以下输出 -
{ "_id" : 101, "AllDetails" : [ { "ImagePath" : "/all/image1", "isCorrect" : "false" }, { "Name" : "Chris", "isCorrect" : "false" } ] }
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
安卓
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP