我试图合并和更新4个字段(名称、面板、部分、分段)相同的对象。
即
数据合并1:名称=“字段手册v1.1”和“节”=“客户”和分节=“手册”和面板=“革命系列(R3系列)”
数据合并2:名称=“现场手册v1.1”和区段=“客户”和分节=“手册”和面板=“生态安全消化器(E3系列)”
初始对象
{
"_id" : ObjectId("5d35e1fd02819f105326c84e"),
"deleted" : false,
"files" : [
{
"ext" : "pdf",
"file" : "Revolution Series Digester Field Handbook R3 Series v1.1 150 DPI.pdf"
}
],
"name" : "Field Handbook v1.1",
"section" : "customer",
"subsection" : "manuals",
"tags" : [
"customer",
"manuals"
],
"panel" : "Revolution Series (R3 Series)"
}
{
"_id" : ObjectId("5d35e1fd02819f105326c851"),
"deleted" : false,
"files" : [
{
"ext" : "link",
"file" : "http://docs.biohitech.com/r3/handbook"
}
],
"name" : "Field Handbook v1.1",
"section" : "customer",
"subsection" : "manuals",
"tags" : [
"customer",
"manuals"
],
"panel" : "Revolution Series (R3 Series)"
}
{
"_id" : ObjectId("5d35e1fd02819f105326c856"),
"deleted" : false,
"files" : [
{
"ext" : "pdf",
"file" : "Eco-Safe Digester Field Handbook E3 Series v1.1 150 DPI.pdf"
}
],
"name" : "Field Handbook v1.1",
"section" : "customer",
"subsection" : "manuals",
"tags" : [
"customer",
"manuals"
],
"panel" : "Eco-Safe Digester (E3 Series)"
}
{
"_id" : ObjectId("5d35e1fd02819f105326c857"),
"deleted" : false,
"files" : [
{
"ext" : "link",
"file" : "http://docs.biohitech.com/e3/handbook/"
}
],
"name" : "Field Handbook v1.1",
"section" : "customer",
"subsection" : "manuals",
"tags" : [
"customer",
"manuals"
],
"panel" : "Eco-Safe Digester (E3 Series)"
}预期结果
{
"_id" : ObjectId("5d35e1fd02819f105326c84e"),
"deleted" : false,
"files" : [
{
"ext" : "pdf",
"file" : "Revolution Series Digester Field Handbook R3 Series v1.1 150 DPI.pdf"
},
{
"ext" : "link",
"file" : "http://docs.biohitech.com/r3/handbook"
}
],
"name" : "Field Handbook v1.1",
"section" : "customer",
"subsection" : "manuals",
"tags" : [
"customer",
"manuals"
],
"panel" : "Revolution Series (R3 Series)"
}
{
"_id" : ObjectId("5d35e1fd02819f105326c856"),
"deleted" : false,
"files" : [
{
"ext" : "pdf",
"file" : "Eco-Safe Digester Field Handbook E3 Series v1.1 150 DPI.pdf"
},
{
"ext" : "link",
"file" : "http://docs.biohitech.com/e3/handbook/"
}
],
"name" : "Field Handbook v1.1",
"section" : "customer",
"subsection" : "manuals",
"tags" : [
"customer",
"manuals"
],
"panel" : "Eco-Safe Digester (E3 Series)"
}发布于 2020-02-10 18:20:26
你可以试试这个:
db.collection.aggregate([
{
$unwind: {
path: "$files",
preserveNullAndEmptyArrays: true
}
},
{
$group: {
_id: {
"name": "$name",
"section": "$section",
"subsection": "$subsection",
"panel": "$panel"
},
data: {
$first: "$$ROOT"
},
files: {
$push: "$files"
}
}
},
{
$addFields: {
"data.files": "$files"
}
},
{
$replaceRoot: {
newRoot: "$data"
}
},
/** writes to new collection named 'collection_new' will override collection if that name already exists */
{ $out: "collection_new" }
])测试: MongoDB-游乐场
一旦您觉得collection_new中的数据是好的,那么您可能需要删除现有的集合&将其重命名为旧的/实际名称,还需要检查索引。如果您可以升级到>4.2,那么可以使用$merge将文档附加到现有的集合中,这在使用上要干净得多。
https://stackoverflow.com/questions/60154845
复制相似问题