MongoDB的$in子句保證訂單當使用MongoDB時$in子句,返回的文檔的順序總是與數組參數的順序相對應嗎?
3 回答

當年話下
TA貢獻1890條經驗 獲得超9個贊
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中是新的,它允許您在不了解所有其他現有字段的情況下對現有文檔“$project”新字段。新的“$indexOfArray”表達式返回給定數組中特定元素的位置。
addToSet
order
order

繁星淼淼
TA貢獻1775條經驗 獲得超11個贊
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 關注
- 1835 瀏覽
添加回答
舉報
0/150
提交
取消