这是我的文档结构:
{
"_id" : ObjectId("5841eba5d3693034c49da7d7"),
"Key" : "01041655",
"matchingKey" : "01041655",
"brand" : "Brand",
"name" : "Product Name",
"availabilities" : [
{
"data1" : [
{
"number_a" : null,
"number_b" : "4.5",
"number_c" : null,
"number_d" : null,
"amount" : 0,
"lastCheck" : "2016-12-02T22:46:13.393+01:00"
},
{
"number_a" : null,
"number_b" : "5",
"number_c" : null,
"number_d" : null,
"amount" : 0,
"lastCheck" : "2016-12-02T22:46:13.393+01:00"
},
{
"number_a" : null,
"number_b" : "5.5",
"number_c" : null,
"number_d" : null,
"amount" : 0,
"lastCheck" : "2016-12-02T22:46:13.393+01:00"
}
]
},
{
"data2" : [
{
"number_a" : null,
"number_b" : "4.5",
"number_c" : null,
"number_d" : null,
"amount" : 0,
"lastCheck" : "2016-12-02T22:46:13.393+01:00"
},
{
"number_a" : null,
"number_b" : "5",
"number_c" : null,
"number_d" : null,
"amount" : 0,
"lastCheck" : "2016-12-02T22:46:13.393+01:00"
}
]
}
]
}
我不确定这是否是最佳方式,所以如果有更好的方法,请告诉我。我的问题是:如何删除数组data1或data2。在Java中最好的方法是什么?我当前的Java代码如下所示:
Document array = new Document("availabilities", dataKey);
Document updateSet = new Document("$unset", array);
prodCollection.updateMany(eq("matchingKey", matchingKey), updateSet);
但是此代码会删除可用性中的所有文档。
UPDATE1: 我改变了文档结构:
{
"_id" : ObjectId("5841eba5d3693034c49da7d7"),
"Key" : "01041655",
"matchingKey" : "01041655",
"brand" : "Brand",
"name" : "Product Name",
"availabilities" : {
"data1" : [
{
"number_a" : null,
"number_b" : "4.5",
"number_c" : null,
"number_d" : null,
"amount" : 0,
"lastCheck" : "2016-12-02T22:46:13.393+01:00"
},
{
"number_a" : null,
"number_b" : "5",
"number_c" : null,
"number_d" : null,
"amount" : 0,
"lastCheck" : "2016-12-02T22:46:13.393+01:00"
},
{
"number_a" : null,
"number_b" : "5.5",
"number_c" : null,
"number_d" : null,
"amount" : 0,
"lastCheck" : "2016-12-02T22:46:13.393+01:00"
}
],
"data2" : [
{
"number_a" : null,
"number_b" : "4.5",
"number_c" : null,
"number_d" : null,
"amount" : 0,
"lastCheck" : "2016-12-02T22:46:13.393+01:00"
},
{
"number_a" : null,
"number_b" : "5",
"number_c" : null,
"number_d" : null,
"amount" : 0,
"lastCheck" : "2016-12-02T22:46:13.393+01:00"
}
]
}
}
现在我可以在mongodb中删除类似的特定数组:
db.products.update({"matchingKey":'01041655'},{$unset: {"availabilities.data1":1}});
我怎么能用Java做到这一点?我这样试过:
Document array = new Document("availabilities.data1", 1);
Document updateSet = new Document("$unset", array);
prodCollection.updateOne(eq("matchingKey", matchingKey), updateSet);
但它仍会删除所有数组。
答案 0 :(得分:0)
我对$ set运算符产生了误解。它用新的数据替换旧数据。因此,我不需要删除该阵列。我只需要在Java中使用$ set:
Document availDoc = new Document("availabilities."+key, availabilities);
Document updateSet = new Document("$set", availDoc);
prodCollection.updateOne(eq("matchingKey", matchingKey), updateSet);