如何按时间对数据进行排序?数组和对象中的数据有一个内部数组,每个对象都在其中创建了值



数据在一个数组中,该数组中的每个对象都有一个内部数组,其中每个对象都具有createdAt值。

因此,我的意图是通过createdAt对它们进行排序。

在该数据中,我希望创建的值内部的data事务进行排序

{
_id: new ObjectId("62f4ba7fb45d837c4872a577"),
balance: 13700,
createdAt: 2022-08-11T08:14:34.086Z,
transactions: [
{
cash: 10000,
due: 1600,
total: 11600,
balance: 1600,
type: 'order',
createdAt: 2022-08-11T15:41:30.729Z,
_id: new ObjectId("62f4cf0190260cd6310f73b7")
},
{
cash: 20000,
due: 5000,
total: 25000,
balance: 6600,
type: 'order',
createdAt: 2022-08-11T15:41:30.729Z,
_id: new ObjectId("62f4cf5190260cd6310f73c4")
},
{
cash: 200,
due: 0,
total: 0,
balance: 6400,
type: 'add-cash',
createdAt: 2022-08-11T16:38:09.561Z,
_id: new ObjectId("62f4dc2c084c7031e0edc770")
},
{
cash: 200,
due: 0,
balance: 13700,
type: 'order',
createdAt: 2022-08-11T10:49:18.390Z,
_id: new ObjectId("62f4df966a3f83c597e20e42")
}
],
__v: 0
}

我试过了,但这是一种错误的方式-_-
const-account=await-account.findOne({userId:userId}(.sort({transactions.createdAt:-1}(;

尝试使用mongo聚合,如:-

collection.aggregate([
{ $unwind: '$transactions' },
{
$sort : { 'transactions.createdAt': -1}
}, 
{
$group: {
_id: '$_id',
balance: {$first: '$balance'},
createdAt: {$first: '$createdAt'},
transactions: {$push: '$transactions'}
}
}
]);

它应该对你有用。

最新更新