我有一个包含如下文档的集合:
{
_id : 1,
code: 1,
state: "FINISHED",
history: //Object
{ 'CREATED': { date: xxx , anotherParam: xxx },
'FINISHED': { date: xxx , anotherParam: xxx }
}
},
{
_id : 2,
code: 1,
state: "CREATED",
history: //Object
{ 'CREATED': { date: xxx , anotherParam: xxx }
},
{
_id : 3,
code: 2,
state: "FINISHED",
history: //Object
{ 'CREATED': { date: xxx , anotherParam: xxx },
'FINISHED': { date: xxx , anotherParam: xxx }
}
}我想做的是一个find查询,在这个查询中,我按照嵌套在历史中的日期对文档进行排序,该日期的关键字是每个文档的状态值。
在前面的示例中,我将按照state的当前值进行排序(在相应的历史关键字=> "history.VALUE_OF_STATE.date"中。
挑战是能够基于状态值在该路径内完成。
例:查询所有编码为== 1的单据,按history.VALUE_OF_EACH_DOCUMENT_STATE.date排序
这应返回文档日期1和文档_id 2,按日期排序,并将文档1的日期视为history.FINISHED.date,文档2的日期为history.CREATED.date
发布于 2021-01-21 18:57:04
使用一些硬编码,因为你只有4种可能的状态:
db.states.aggregate([
{ $match: { code: 1 } },
{
$project: {
_id: 1,
code: 1,
state: 1,
history: 1,
sortingField: {
$switch: {
branches: [
{
case: { $eq: ["$state", "CREATED"] },
then: "$history.CREATED.date",
},
{
case: { $eq: ["$state", "FINISHED"] },
then: "$history.FINISHED.date",
},
],
},
},
},
},
{
$sort: { sortingField: 1 },
},
]);https://stackoverflow.com/questions/65824236
复制相似问题