为此,请aggregate()
在MongoDB中使用。让我们创建一个包含文档的集合-
> 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 }