为此,请使用MongoDB聚合,并在其中使用$cond。在$cond表达式一个布尔表达式返回两个指定回报表现之一。
首先让我们创建一个包含文档的集合-
> db.demo536.insertOne({"Name1":"Chris","Name2":"David"});{ "acknowledged" : true, "insertedId" : ObjectId("5e8c843eef4dcbee04fbbc01") } > db.demo536.insertOne({"Name1":"David","Name2":"Chris"});{ "acknowledged" : true, "insertedId" : ObjectId("5e8c843fef4dcbee04fbbc02") } > db.demo536.insertOne({"Name1":"Bob","Name2":"Sam"});{ "acknowledged" : true, "insertedId" : ObjectId("5e8c843fef4dcbee04fbbc03") } > db.demo536.insertOne({"Name1":"Chris","Name2":"David"});{ "acknowledged" : true, "insertedId" : ObjectId("5e8c843fef4dcbee04fbbc04") }
在find()
方法的帮助下显示集合中的所有文档-
> db.demo536.find();
这将产生以下输出-
{ "_id" : ObjectId("5e8c843eef4dcbee04fbbc01"), "Name1" : "Chris", "Name2" : "David" } { "_id" : ObjectId("5e8c843fef4dcbee04fbbc02"), "Name1" : "David", "Name2" : "Chris" } { "_id" : ObjectId("5e8c843fef4dcbee04fbbc03"), "Name1" : "Bob", "Name2" : "Sam" } { "_id" : ObjectId("5e8c843fef4dcbee04fbbc04"), "Name1" : "Chris", "Name2" : "David" }
以下是将多个字段分组的查询-
> db.demo536.aggregate([ ... { ... $project: ... { ... FirstName1: ... { ... $cond: { if: { $gte: [ "$Name1", "$Name2" ] }, then: "$Name2", else: "$Name1" } ... }, ... FirstName2: ... { ... $cond: { if: { $lt: [ "$Name1", "$Name2" ] }, then: "$Name2", else: "$Name1" } ... } ... } ... } ... ,{ ... $group: ... { ... _id: ... { ... Name1: "$FirstName1", ... Name2: "$FirstName2" ... } ... ,count: { $sum: 1} ... } ... } ... ])
这将产生以下输出&imnus;。
{ "_id" : { "Name1" : "Bob", "Name2" : "Sam" }, "count" : 1 } { "_id" : { "Name1" : "Chris", "Name2" : "David" }, "count" : 3 }