要按单词排序,请使用$addField和$cond。让我们创建一个包含文档的集合
> db.demo62.insertOne({"Subject":"MySQL"}); { "acknowledged" : true, "insertedId" : ObjectId("5e287084cfb11e5c34d8992f") } > db.demo62.insertOne({"Subject":"MongoDB"}); { "acknowledged" : true, "insertedId" : ObjectId("5e287085cfb11e5c34d89930") } > db.demo62.insertOne({"Subject":"Java"}); { "acknowledged" : true, "insertedId" : ObjectId("5e287086cfb11e5c34d89931") }
在find方法的帮助下显示集合中的所有文档-
> db.demo62.find();
这将产生以下输出-
{ "_id" : ObjectId("5e287084cfb11e5c34d8992f"), "Subject" : "MySQL" } { "_id" : ObjectId("5e287085cfb11e5c34d89930"), "Subject" : "MongoDB" } { "_id" : ObjectId("5e287086cfb11e5c34d89931"), "Subject" : "Java" }
以下是按单词排序的查询-
> db.demo62.aggregate([ ... { ... $addFields: { ... sortByWords: { ... $cond: [ ... { $eq: ["$Subject", "MongoDB"] }, ... 0, ... { $cond: [{ $eq: ["$Subject", "MySQL"] }, 1, 2] } ... ] ... } ... } ... }, ... ... { ... $sort: { ... sortByWords: 1 ... } ... } ... ]);
这将产生以下输出-
{ "_id" : ObjectId("5e287085cfb11e5c34d89930"), "Subject" : "MongoDB", "sortByWords" : 0 } { "_id" : ObjectId("5e287084cfb11e5c34d8992f"), "Subject" : "MySQL", "sortByWords" : 1 } { "_id" : ObjectId("5e287086cfb11e5c34d89931"), "Subject" : "Java", "sortByWords" : 2 }