按单词排序的 MongoDB 查询
要按单词排序,请将 $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 }
广告