Does MongoDB's $in clause guarantee order

后端 未结 10 1248
春和景丽
春和景丽 2020-11-22 01:39

When using MongoDB\'s $in clause, does the order of the returned documents always correspond to the order of the array argument?

10条回答
  •  你的背包
    2020-11-22 02:00

    An easy way to order the result after mongo returns the array is to make an object with id as keys and then map over the given _id's to return an array that is correctly ordered.

    async function batchUsers(Users, keys) {
      const unorderedUsers = await Users.find({_id: {$in: keys}}).toArray()
      let obj = {}
      unorderedUsers.forEach(x => obj[x._id]=x)
      const ordered = keys.map(key => obj[key])
      return ordered
    }
    

提交回复
热议问题