如果你不喜歡排序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數組 - 條件和額外的重量值。是這樣嗎? –
因爲我們需要在結果文檔中包含匹配和不匹配的條件,所以我們需要確保從匹配文檔開始,我們會引入重量並按其排序以推送匹配的文檔。 –