即使其中一些值为空,也可以实现 MongoDB $concatArrays 吗?
为此,请使用聚合框架以及 $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" ] }
广告