为此,请使用聚合框架以及$ifNull运算符。聚合中的$concatArrays用于连接数组。首先让我们创建一个包含文档的集合-
>db.concatenateArraysDemo.insertOne({"FirstSemesterSubjects": ["MongoDB","MySQL","Java"],"SecondSemesterSubjects":["C","C++",]}); { "acknowledged" : true, "insertedId" : ObjectId("5cd687707924bb85b3f4895c") } > db.concatenateArraysDemo.insertOne({"FirstSemesterSubjects":["C#","Ruby","Python"]}); { "acknowledged" : true, "insertedId" : ObjectId("5cd687927924bb85b3f4895d") } >db.concatenateArraysDemo.insertOne({"FirstSemesterSubjects":["HTML","CSS","Javascript"],"SecondSemesterSubjects":["CSS","Javascript"]}); { "acknowledged" : true, "insertedId" : ObjectId("5cd687bb7924bb85b3f4895e") }
以下是在find()
方法的帮助下显示集合中所有文档的查询-
> db.concatenateArraysDemo.find().pretty();
这将产生以下输出-
{ "_id" : ObjectId("5cd687707924bb85b3f4895c"), "FirstSemesterSubjects" : [ "MongoDB", "MySQL", "Java" ], "SecondSemesterSubjects" : [ "C", "C++" ] } { "_id" : ObjectId("5cd687927924bb85b3f4895d"), "FirstSemesterSubjects" : [ "C#", "Ruby", "Python" ] } { "_id" : ObjectId("5cd687bb7924bb85b3f4895e"), "FirstSemesterSubjects" : [ "HTML", "CSS", "Javascript" ], "SecondSemesterSubjects" : [ "CSS", "Javascript" ] }
以下是即使为null时也要连接数组的查询-
> db.concatenateArraysDemo.aggregate([ {$project: { ConcatenateArrays: { '$concatArrays': [ {$ifNull: ['$FirstSemesterSubjects', []]}, {$ifNull: ['$SecondSemesterSubjects', []]} ] } } } ]);
这将产生以下输出-
{ "_id" : ObjectId("5cd687707924bb85b3f4895c"), "ConcatenateArrays" : [ "MongoDB", "MySQL", "Java", "C", "C++" ] } { "_id" : ObjectId("5cd687927924bb85b3f4895d"), "ConcatenateArrays" : [ "C#", "Ruby", "Python" ] } { "_id" : ObjectId("5cd687bb7924bb85b3f4895e"), "ConcatenateArrays" : [ "HTML", "CSS", "Javascript", "CSS", "Javascript" ] }