如果你不喜欢排序weight
使用可以看我的选择是使用aggregate
与引入额外场weight
例如脚本拉升匹配文档,然后和限制总的结果:
db.test.aggregate({
$project: {
type: 1,
details: 1,
at: 1,
weight: {
$cond: [
{ "$or": [
{$eq: ["$type", "One"] },
{$eq: ["$type", "Two"] }
] },
0, 1] }
} },
{$sort: {weight: 1}},
{ $limit : 5 }
);
关于这个例子的注释。为了简单起见,我用几个等于$的元素替换$ in。如果您不想在最终结果中包含weight
,则可以通过在聚合管道中应用另一个投影来将其删除。
测试分贝:
> db.test.find({})
{ "_id" : ObjectId("58067329a7518db4d3d2e973"), "type" : "One", "details" : "This is one", "at" : "some place, where one is relevant" }
{ "_id" : ObjectId("5806733da7518db4d3d2e974"), "type" : "Two", "details" : "This is two", "at" : "some place, where one is relevant" }
{ "_id" : ObjectId("5806734ba7518db4d3d2e975"), "type" : "Three", "details" : "This is three", "at" : "some place, where one is relevant" }
{ "_id" : ObjectId("58067374a7518db4d3d2e976"), "type" : "Four", "details" : "This is four", "at" : "some place, where one is relevant" }
{ "_id" : ObjectId("58067381a7518db4d3d2e977"), "type" : "Five", "details" : "This is five", "at" : "some place, where one is relevant" }
{ "_id" : ObjectId("5806738fa7518db4d3d2e978"), "type" : "Six", "details" : "This is six", "at" : "some place, where one is relevant" }
{ "_id" : ObjectId("580673cfa7518db4d3d2e979"), "type" : "Seven", "details" : "This is seven", "at" : "some place, where one is relevant" }
结果:
> db.test.aggregate({ $project: { type: 1, details: 1, at: 1, weight: { $cond: [ { "$or": [ {$eq: ["$type", "One"] }, {$eq: ["$type", "Two"] } ] }, 0, 1] } } }, {$sort: {weight: 1}}, { $limit : 5 }, {$project: {type: 1, details: 1, at: 1} });
{ "_id" : ObjectId("58067329a7518db4d3d2e973"), "type" : "One", "details" : "This is one", "at" : "some place, where one is relevant" }
{ "_id" : ObjectId("5806733da7518db4d3d2e974"), "type" : "Two", "details" : "This is two", "at" : "some place, where one is relevant" }
{ "_id" : ObjectId("58067374a7518db4d3d2e976"), "type" : "Four", "details" : "This is four", "at" : "some place, where one is relevant" }
{ "_id" : ObjectId("58067381a7518db4d3d2e977"), "type" : "Five", "details" : "This is five", "at" : "some place, where one is relevant" }
{ "_id" : ObjectId("5806734ba7518db4d3d2e975"), "type" : "Three", "details" : "This is three", "at" : "some place, where one is relevant" }
完美@麦克 - shauneu!完美的作品! 我不禁注意到,在这个例子中,我们只有两个可能的权重 - 我假设一个用于条件匹配(so,0)和不匹配(so,1),然后按重量排序。 但是我们可以有更多的权重? 我认为应该追加到$ cond数组 - 条件和额外的重量值。是这样吗? –
因为我们需要在结果文档中包含匹配和不匹配的条件,所以我们需要确保从匹配文档开始,我们会引入重量并按其排序以推送匹配的文档。 –