如果 0 后跟 >=1 从 MongoDB 中的数组中删除 0 值 [英] remove 0 values if 0 is followed by >=1 from arrays in MongoDB
本文介绍了如果 0 后跟 >=1 从 MongoDB 中的数组中删除 0 值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在 data_start
中,如果 0 后跟 >=1 则从 data_start
中删除 0,同时从 time_start中删除元素代码>相应的数组.
输出文件将是:
<代码>{数据开始":[1、1、0,1、1、0],时间开始":[2021-09-04T12:18:42Z",2021-09-04T14:59:50Z",2021-09-04T14:59:59Z",2021-09-04T15:00:01Z",2021-09-04T15:05:00Z",2021-09-04T15:05:01Z"]}
解决方案
一种方法是这样的:
db.collection.aggregate([{$set:{数据: {$let: {变量:{val:$data_start",prev: { $concatArrays: [[null], "$data_start"] }//将值移动一个元素},在: {$地图:{输入:{ $range: [0, { $size: "$$val";}] },如:idx",在: {$cond: {如果: {$和:[{ $eq: [{ $arrayElemAt: ["$$val", "$$idx"] }, 0] },//是 0{ $eq: [{ $arrayElemAt: ["$$val", "$$idx"] }, { $arrayElemAt: ["$$prev", "$$idx"] }] }//等于之前]},然后:空,别的: {data_start: { $arrayElemAt: ["$$val", "$$idx"] },time_start: { $arrayElemAt: ["$time_start", "$$idx"] }}}}}}}}}},{$set:{数据: {$过滤器:{输入:$数据",条件:$$this"//->从数组中删除空值}}}}])
也许您必须微调条件和/或反转循环,即 input: { $range: [{ $size: "$$val"}, 0, -1] }
In data_start
if 0 is followed by >=1 in the array then remove the 0 from the data_start
, also remove the element from time_start
array accordingly.
{
"data_start": [
1,
1,
0,
0,
1,
1,
0
],
"time_start": [
"2021-09-04T12:18:42Z",
"2021-09-04T14:59:50Z",
"2021-09-04T14:59:59Z",
"2021-09-04T15:00:00Z",
"2021-09-04T15:00:01Z",
"2021-09-04T15:05:00Z",
"2021-09-04T15:05:01Z"
]
}
Output Document will be :
{
"data_start": [
1,
1,
0,
1,
1,
0
],
"time_start": [
"2021-09-04T12:18:42Z",
"2021-09-04T14:59:50Z",
"2021-09-04T14:59:59Z",
"2021-09-04T15:00:01Z",
"2021-09-04T15:05:00Z",
"2021-09-04T15:05:01Z"
]
}
解决方案
One approach is this one:
db.collection.aggregate([
{
$set: {
data: {
$let: {
vars: {
val: "$data_start",
prev: { $concatArrays: [[null], "$data_start"] } // shift values by one element
},
in: {
$map: {
input: { $range: [0, { $size: "$$val" }] },
as: "idx",
in: {
$cond: {
if: {
$and: [
{ $eq: [{ $arrayElemAt: ["$$val", "$$idx"] }, 0] }, // is 0
{ $eq: [{ $arrayElemAt: ["$$val", "$$idx"] }, { $arrayElemAt: ["$$prev", "$$idx"] }] } // is equal to previous
]
},
then: null,
else: {
data_start: { $arrayElemAt: ["$$val", "$$idx"] },
time_start: { $arrayElemAt: ["$time_start", "$$idx"] }
}
}
}
}
}
}
}
}
},
{
$set: {
data: {
$filter: {
input: "$data",
cond: "$$this"// -> removes null's from array
}
}
}
}
])
Maybe you have to fine-tune the condition and/or reverse the loop, i.e. input: { $range: [{ $size: "$$val" }, 0, -1] }
这篇关于如果 0 后跟 >=1 从 MongoDB 中的数组中删除 0 值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文