หากต้องการรวมหลายอาร์เรย์เป็นอาร์เรย์เดียว ให้ใช้ $project ใน MongoDB ให้เราสร้างคอลเลกชันที่มีเอกสาร -
> 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" } ] }