以下是按项目查询MongoDB并按降序排列反向数组的解决方法的代码示例:
const MongoClient = require('mongodb').MongoClient;
// 连接 MongoDB 数据库
MongoClient.connect('mongodb://localhost:27017', { useUnifiedTopology: true })
.then(client => {
// 指定数据库和集合
const db = client.db('mydatabase');
const collection = db.collection('mycollection');
// 查询并按项目降序排列
collection.find({}).sort({ _id: -1 }).toArray()
.then(results => {
// 反向数组
const reversedArray = results.reverse();
console.log(reversedArray);
})
.catch(error => {
console.error(error);
})
.finally(() => {
// 关闭数据库连接
client.close();
});
})
.catch(error => {
console.error(error);
});
上述代码使用了mongodb
模块来连接MongoDB数据库,并按照指定的项目进行查询。在sort()
函数中,我们使用_id
字段进行降序排列。然后,使用toArray()
方法将查询结果转换为数组,并使用reverse()
方法反向该数组。最后,打印出反向的数组。请根据实际情况修改数据库连接字符串、数据库名称和集合名称。