如何使用节点js对mongoDB中集合内的数组进行排序
how to sort array inside collection in mongoDB using node js
我有一个查询集合,存储在记录上的数据看起来像following.i想根据数组中的id或日期降序排列
[
{
"_id": "5e71fa3ab004192b349e4a06",
"QUERIES": [
{
"_id": "5e71fa3ab004192b349e4a07",
"QUERY": "1",
"USER_ID": "5e6f1c5b8451307f782d0994",
"USER_NAME": "a2",
"createdAt": "2020-03-18T10:38:50.247Z"
},
{
"_id": "5e71fa46b004192b349e4a08",
"QUERY": "2",
"USER_ID": "5e6f1c5b8451307f782d0994",
"USER_NAME": "a1",
"createdAt": "2020-03-18T10:39:02.451Z"
}
],
"TICKET_ID": "5e70f4fa47df9479502f7937"
]
预期产出
[
{
"_id": "5e71fa3ab004192b349e4a06",
"QUERIES": [
{
"_id": "5e71fa46b004192b349e4a08",
"QUERY": "2",
"USER_ID": "5e6f1c5b8451307f782d0994",
"USER_NAME": "a1",
"createdAt": "2020-03-18T10:39:02.451Z"
},
{
"_id": "5e71fa3ab004192b349e4a07",
"QUERY": "1",
"USER_ID": "5e6f1c5b8451307f782d0994",
"USER_NAME": "a2",
"createdAt": "2020-03-18T10:38:50.247Z"
}
],
"TICKET_ID": "5e70f4fa47df9479502f7937"
]
使用这个:
db.collection.aggregate([
{ $unwind: "$QUERIES" },
{ $sort: { "QUERIES.createdAt": -1 } },
{
$group: {
_id: { _id: "$_id", TICKET_ID: "$TICKET_ID" },
QUERIES: { $push: "$QUERIES" }
}
},
{ $replaceRoot: { newRoot: { $mergeObjects: ["$$ROOT", "$_id"] } } }
])
我有一个查询集合,存储在记录上的数据看起来像following.i想根据数组中的id或日期降序排列
[
{
"_id": "5e71fa3ab004192b349e4a06",
"QUERIES": [
{
"_id": "5e71fa3ab004192b349e4a07",
"QUERY": "1",
"USER_ID": "5e6f1c5b8451307f782d0994",
"USER_NAME": "a2",
"createdAt": "2020-03-18T10:38:50.247Z"
},
{
"_id": "5e71fa46b004192b349e4a08",
"QUERY": "2",
"USER_ID": "5e6f1c5b8451307f782d0994",
"USER_NAME": "a1",
"createdAt": "2020-03-18T10:39:02.451Z"
}
],
"TICKET_ID": "5e70f4fa47df9479502f7937"
]
预期产出
[
{
"_id": "5e71fa3ab004192b349e4a06",
"QUERIES": [
{
"_id": "5e71fa46b004192b349e4a08",
"QUERY": "2",
"USER_ID": "5e6f1c5b8451307f782d0994",
"USER_NAME": "a1",
"createdAt": "2020-03-18T10:39:02.451Z"
},
{
"_id": "5e71fa3ab004192b349e4a07",
"QUERY": "1",
"USER_ID": "5e6f1c5b8451307f782d0994",
"USER_NAME": "a2",
"createdAt": "2020-03-18T10:38:50.247Z"
}
],
"TICKET_ID": "5e70f4fa47df9479502f7937"
]
使用这个:
db.collection.aggregate([
{ $unwind: "$QUERIES" },
{ $sort: { "QUERIES.createdAt": -1 } },
{
$group: {
_id: { _id: "$_id", TICKET_ID: "$TICKET_ID" },
QUERIES: { $push: "$QUERIES" }
}
},
{ $replaceRoot: { newRoot: { $mergeObjects: ["$$ROOT", "$_id"] } } }
])