我想从我的MongoDB对象中删除($reduce(元素,条件是同一个对象有相似的元素。我的目标:
{
"_id": "5eabf8b144345b36b00bfbaa",
"ranktime": [
{
"pos": "15",
"datum": "Mon May 01 2020 12:25:14 GMT+0200 (GMT+02:00)",
"source": "SOURCE2"
},
{
"pos": "10",
"datum": "Fri May 05 2020 12:25:14 GMT+0200 (GMT+02:00)",
"source": "SOURCE2"
},
{
"pos": "15",
"datum": "Mon May 01 2020 18:45:27 GMT+0200 (GMT+02:00)",
"source": "SOURCE2"
},
{
"pos": "20",
"datum": "Fri May 05 2020 18:45:27 GMT+0200 (GMT+02:00)",
"source": "SOURCE1"
},
{
"pos": "10",
"datum": "Fri May 05 2020 12:25:14 GMT+0200 (GMT+02:00)",
"source": "SOURCE2"
},
{
"pos": "15",
"datum": "Mon May 01 2020 18:45:27 GMT+0200 (GMT+02:00)",
"source": "SOURCE2"
}
]
}
因此,如果ranktime.source==";来源2";以及日期是否与之前的对象相同。实际上,我必须遍历ranktime的单个元素。这在MongoDB中可能吗?
预期结果是:
{
"_id": "5eabf8b144345b36b00bfbaa",
"ranktime": [
{
"pos": "15",
"datum": "Mon May 01 2020 12:25:14 GMT+0200 (GMT+02:00)",
"source": "SOURCE2"
},
{
"pos": "10",
"datum": "Fri May 05 2020 12:25:14 GMT+0200 (GMT+02:00)",
"source": "SOURCE2"
},
{
"pos": "20",
"datum": "Fri May 05 2020 18:45:27 GMT+0200 (GMT+02:00)",
"source": "SOURCE1"
}
]
}
因此,根据您的示例,您希望输出ranktime
,除非是SOURCE2
并且已经将相同的日期添加到输出中(但仅适用于SOURCE2
(。
您可以像以前一样使用$reduce
,但您需要扫描以前添加的元素,这可以使用$anyElementTrue运算符来实现。由于您的输出包含第三个元素,我假设只有在为SORUCE2
添加了相同日期的情况下,重复日期才是停止条件,因此还需要$filter来准备以前添加的SOURCE2
的集合:
db.col.updateMany({}, [
{
$set: {
ranktime: {
$reduce: {
input: "$ranktime",
initialValue: [],
in: {
$cond: [
{
$and: [
{ "$eq": [ "$$this.source", "SOURCE2" ] },
{
$anyElementTrue: {
$map: {
input: { $filter: { input: "$$value", as: "prev", cond: { $eq: { "$$prev.source", "SOURCE2" } } } }, // already added SOURCE2 elements
as: "addedElement",
in: { "$eq": [ { $substr: [ "$$addedElement.datum", 0, 15 ] }, { $substr: [ "$$this.datum", 0, 15 ] } ] }
}
}
}
]
},
"$$value", // skip current element ($$this)
{ $concatArrays: [ "$$value", [ "$$this" ] ] } // add current element to the output
]
}
}
}
}
}
])
Mongo游乐场