如果同一个对象有相似的元素,我想从我的MongoDB对象中删除($unset(元素。我的目标:
{
"_id": "5eabf8b144345b36b00bfbaa",
"ranktime": [{
"pos":"2",
"datum":"Mon May 05 2020 12:22:52 GMT+0200 (GMT+02:00)",
"source":"SOURCE2"
},{
"pos":"1",
"datum":"Fri May 01 2020 12:23:10 GMT+0200 (GMT+02:00)",
"source":"SOURCE1"
},{
"pos":"37",
"datum":"Fri May 01 2020 12:25:14 GMT+0200 (GMT+02:00)",
"source":"SOURCE2"
},{
"pos":"12",
"datum":"Fri May 01 2020 12:25:14 GMT+0200 (GMT+02:00)",
"source":"SOURCE2"
},{
"pos":"37",
"datum":"Fri May 01 2020 18:45:27 GMT+0200 (GMT+02:00)",
"source":"SOURCE2"
}]
}
因此,如果ranktime.source == "SOURCE2"
并且日期与之前的对象相同,我想删除ranktime
中的条目。实际上,我必须遍历ranktime
的单个元素。这在MongoDB中可能吗?
预期结果是:
{
"_id": "5eabf8b144345b36b00bfbaa",
"ranktime": [{
"pos":"2",
"datum":"Mon May 05 2020 12:22:52 GMT+0200 (GMT+02:00)",
"source":"SOURCE2"
},{
"pos":"1",
"datum":"Fri May 01 2020 12:23:10 GMT+0200 (GMT+02:00)",
"source":"SOURCE1"
},{
"pos":"37",
"datum":"Fri May 01 2020 12:25:14 GMT+0200 (GMT+02:00)",
"source":"SOURCE2"
}]
}
基本上,您可以使用$reduce来处理数组,并使用$let和$arrayElemAt语句定义上一个元素。新的$set语法允许您在更新语句中使用聚合:
db.col.updateMany({}, [
{
$set: {
ranktime: {
$reduce: {
input: "$ranktime",
initialValue: [],
in: {
$let: {
vars: { last: { $arrayElemAt: [ "$$value", -1 ] } },
in: {
$cond: [
{
$and: [
{ "$eq": [ "$$last.source", "SOURCE2" ] },
{ "$eq": [ { $substr: [ "$$last.datum", 0, 15 ] }, { $substr: [ "$$this.datum", 0, 15 ] } ] },
]
},
"$$value",
{ $concatArrays: [ "$$value", [ "$$this" ] ] }
]
}
}
}
}
}
}
}
])
聚合示例