Để tổng hợp nhiều mảng thành một mảng, hãy sử dụng $ project trong MongoDB. Hãy để chúng tôi tạo một bộ sưu tập với các tài liệu -
> 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 } Hiển thị tất cả các tài liệu từ một bộ sưu tập với sự trợ giúp của phương thức find () -
> db.demo119.find();
Điều này sẽ tạo ra kết quả sau -
{
"_id" : 101, "WebDetails" : [
{ "ImagePath" : "/all/image1", "isCorrect" : "false" },
{ "ImagePath" : "/all/image2", "isCorrect" : "true" } ], "ClientDetails" : [
{ "Name" : "Chris", "isCorrect" : "false" }, { "Name" : "David", "isCorrect" : "true" }
]
} Sau đây là truy vấn để tổng hợp nhiều mảng thành một mảng duy nhất với 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 } } }
... ]) Điều này sẽ tạo ra kết quả sau -
{ "_id" : 101, "AllDetails" : [ { "ImagePath" : "/all/image1", "isCorrect" : "false" }, { "Name" : "Chris", "isCorrect" : "false" } ] }