3 回答

TA貢獻(xiàn)1890條經(jīng)驗(yàn) 獲得超9個(gè)贊
var order = [ "David", "Charlie", "Tess" ];
var query = [ {$match: {name: {$in: order}}}, {$addFields: {"__order": {$indexOfArray: [order, "$name" ]}}}, {$sort: {"__order": 1}} ];var result = db.users.aggregate(query);
“$addField”階段在3.4中是新的,它允許您在不了解所有其他現(xiàn)有字段的情況下對(duì)現(xiàn)有文檔“$project”新字段。新的“$indexOfArray”表達(dá)式返回給定數(shù)組中特定元素的位置。
addToSet
order
order

TA貢獻(xiàn)1775條經(jīng)驗(yàn) 獲得超11個(gè)贊
aggregate
find
array#sort
:
$in
var ids = [4, 2, 8, 1, 9, 3, 5, 6];MyModel.find({ _id: { $in: ids } }).exec(function(err, docs) { docs.sort(function(a, b) { // Sort docs by the order of their _id values in ids. return ids.indexOf(a._id) - ids.indexOf(b._id); });});
$in
ObjectId
indexOf
Array#findIndex
ObjectID#equals
sort
docs.sort((a, b) => ids.findIndex(id => a._id.equals(id)) - ids.findIndex(id => b._id.equals(id)));
findIndex
:
docs.sort(function (a, b) { return _.findIndex(ids, function (id) { return a._id.equals(id); }) - _.findIndex(ids, function (id) { return b._id.equals(id); });});
- 3 回答
- 0 關(guān)注
- 1846 瀏覽
添加回答
舉報(bào)