我有一个 mongo 集合,其中的文档组织如下:
{
"_id" : ObjectId("5ea084718a475ee5faaaf3b7"),
"vehicleid" : 32040,
"date" : ISODate("2018-02-01T00:00:00Z"),
"points" : {
"direction" : 135,
"latitude" : -3.744851,
"longitude" : -38.545571,
"odometer" : 55697826,
"routecode" : 0,
"speed" : 3,
"deviceid" : 134680,
"metrictimestamp" : ISODate("2018-02-01T02:59:59Z")
}
}
{
"_id" : ObjectId("5ea084718a475ee5faaaf3b8"),
"vehicleid" : 32040,
"date" : ISODate("2018-02-01T00:00:00Z"),
"points" : {
"direction" : 270,
"latitude" : -3.840556,
"longitude" : -38.4954,
"odometer" : 24358799,
"routecode" : 0,
"speed" : 0,
"deviceid" : 97878,
"metrictimestamp" : ISODate("2018-02-01T02:59:19Z")
}
}
我需要一种通过创建新的“点”字段来更新集合的方法,该字段将是具有相同“vehicleid”和“日期”的所有文档中所有“点”对象的数组,例如:
{
"_id" : ObjectId("5ea084718a475ee5faaaf3b8"),
"vehicleid" : 32040,
"date" : ISODate("2018-02-01T00:00:00Z"),
"points" : [{
"direction" : 270,
"latitude" : -3.840556,
"longitude" : -38.4954,
"odometer" : 24358799,
"routecode" : 0,
"speed" : 0,
"deviceid" : 97878,
"metrictimestamp" : ISODate("2018-02-01T02:59:19Z")
},
{
"direction" : 135,
"latitude" : -3.744851,
"longitude" : -38.545571,
"odometer" : 55697826,
"routecode" : 0,
"speed" : 3,
"deviceid" : 134680,
"metrictimestamp" : ISODate("2018-02-01T02:59:59Z")
}]
}
有什么想法吗???
最佳答案
是的,您可以使用 MongoDB 中的 $out
来实现
这是相同的 shell 查询:
我将保持第二个集合的名称不同,如果您想更新同一个集合,则可以保持集合的名称相同。
注意 $out
将用聚合的输出替换集合中已有的所有文档,直到最后阶段。所以,你最好小心处理。
db.first_collection.aggregate([
{
$project:{
"_id":0
}
},
{
$group:{
"_id":{
"vehicleid":"$vehicleid",
"date":"$date"
},
"date":{
$first:"$date"
},
"vehicleid":{
$first:"$vehicleid"
},
"points":{
$push:"$points"
}
}
},
{
$project:{
"_id":0
}
},
{
$out:"second_collection"
}
])
有关 $out
的更多信息,请阅读 here 。
希望这会有所帮助:)
关于mongodb - 更新文档并创建一个字段,该字段是集合 MongoDB 中具有相同 id 的所有对象的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61415530/