我想在我的MongoDB集合更新單個文檔MongoDB的MongoCollection:無法更新場
JSONArray jsonArr = new JSONArray();
/*Some processing to add stuff to jsonArr*/
mongoCollection.updateOne(eq("key", _id),Updates.set("asd", jsonArr));
,但我得到
org.bson.codecs.configuration.CodecConfigurationException: Can't find a codec for class org.json.simple.JSONObject.
at org.bson.codecs.configuration.CodecCache.getOrThrow(CodecCache.java:46)
at org.bson.codecs.configuration.ProvidersCodecRegistry.get(ProvidersCodecRegistry.java:63)
at org.bson.codecs.configuration.ChildCodecRegistry.get(ChildCodecRegistry.java:51)
at org.bson.codecs.IterableCodec.writeValue(IterableCodec.java:105)
at org.bson.codecs.IterableCodec.encode(IterableCodec.java:90)
at org.bson.codecs.IterableCodec.encode(IterableCodec.java:37)
at com.mongodb.client.model.BuildersHelper.encodeValue(BuildersHelper.java:35)
at com.mongodb.client.model.Updates$SimpleUpdate.toBsonDocument(Updates.java:442)
at com.mongodb.MongoCollectionImpl.toBsonDocument(MongoCollectionImpl.java:599)
at com.mongodb.MongoCollectionImpl.update(MongoCollectionImpl.java:542)
at com.mongodb.MongoCollectionImpl.updateOne(MongoCollectionImpl.java:381)
at com.mongodb.MongoCollectionImpl.updateOne(MongoCollectionImpl.java:376)
需要注意的是,這裏是我最初創建的文件在第一
Document unprocessedMeta = new Document("key",_id);
JSONArray arr = new JSONArray();
/*some processing to add stuff to arr */
unprocessedMeta.append("asd", arr);
mongoCollection.insertOne(unprocessedMeta);
這工作得很好。 請注意,asd
密鑰的值爲JSONArray
。另外,我可以通過
Document d = mongoCollection.find(eq("key", _id)).first();
選擇文檔,它顯示了與預期
Document{{_id=5981e702324fb0b50d727fe7, key=2323, asd=[Document{{<some-key-value-pairs>}}]}}
,我可以得到內JSONArray
作爲
JSONArray existingAsd = (JSONArray) d.get("asd");
,我可以遍歷通過existingAsd
並訪問對象。
爲什麼不能更新?基本上,我想替換與key
匹配的文檔中的密鑰asd
的值。我甚至試過
mongoCollection.updateOne(eq("key", _id),Updates.unset("asd"));
mongoCollection.updateOne(eq("key", _id),Updates.set("asd", jsonArr));
,但我得到了同樣的錯誤
謝謝,工作! – AbtPst