用于排名/搜索计数的 MongoDB 查询?
为此,在 MongoDB 中使用 aggregate()。让我们创建一个带文档的集合 −
> db.demo120.insertOne( ... { ... 'Name': 'Chris', ... 'Subjects': [ 'MySQL', 'MongoDB', 'Java', 'Python' ] ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5e2f11aed8f64a552dae6365") } > db.demo120.insertOne( ... { ... 'Name': 'Bob', ... 'Subjects': [ 'C', 'MongoDB' ] ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5e2f11afd8f64a552dae6366") }
借助 find() 方法从集合中显示所有文档 −
> db.demo120.find();
这将生成以下输出 −
{ "_id" : ObjectId("5e2f11aed8f64a552dae6365"), "Name" : "Chris", "Subjects" : [ "MySQL", "MongoDB", "Java", "Python" ] } { "_id" : ObjectId("5e2f11afd8f64a552dae6366"), "Name" : "Bob", "Subjects" : [ "C", "MongoDB" ] }
以下是 MongoDB 排名/搜索计数的查询 −
> var s = ['MySQL', 'Java', 'MongoDB']; > db.demo120.aggregate([ ... { "$match": { "Subjects": { "$in": s } } }, ... { ... "$addFields": { ... "RankSearch": { ... "$divide": [ ... { "$size": { "$setIntersection": ["$Subjects",s] } }, ... { "$size": "$Subjects" } ... ] ... } ... } ... }, ... { "$sort": { "RankSearch": -1 } } ... ])
这将生成以下输出 −
{ "_id" : ObjectId("5e2f11aed8f64a552dae6365"), "Name" : "Chris", "Subjects" : [ "MySQL", "MongoDB", "Java", "Python" ], "RankSearch" : 0.75 } { "_id" : ObjectId("5e2f11afd8f64a552dae6366"), "Name" : "Bob", "Subjects" : [ "C", "MongoDB" ], "RankSearch" : 0.5 }
广告