将通过 Java 驱动程序与数组元素以及 MongoDB 中的普通 ID 一起工作

Will upsert work with array Elements as well as the normal ID in MongoDB through Java driver

Mongo 数据库包含以下数据:

要求是如果在此文档中存在一个字段,则计数器会增加,否则插入该字段。 通常,当我们不确定它是否会被插入或 Update.But 是否适用时,我们会使用 upsert 还有数组元素

db.arrayexample.find()

{ "_id" : "userID", "addresses" : [  {  "arrayid" : NumberLong(16694),  "count" : 12 } ] }

我的Java代码如下:

MongoClient mongoClient = new MongoClient("localhost", 27017);
MongoDatabase mongoDatabase = mongoClient.getDatabase("testdb3");
MongoCollection mongoCollection = mongoDatabase.getCollection("arrayexample");
    BasicDBObject query = new BasicDBObject();
query.put("_id", "userID");
query.put("addresses.arrayid",Long.valueOf(16695) );
    mongoCollection.findOneAndUpdate(query,new Document("$inc", new Document("addresses.$.count", 1)),new FindOneAndUpdateOptions().upsert(true));

当我 运行 程序时出现以下错误:

'exception: Cannot apply the positional operator without a corresponding query field containing an array.' 服务器 localhost:27017。完整的回复是

 "value" : null, "errmsg" : "exception: Cannot apply the positional operator without a corresponding query field containing an array.", "code" : 16650,

$Upset 可以与数组元素以及普通 ID 一起使用吗

不,如 MongoDB 文档中所述,使用 $positional 运算符时更新插入将不起作用。

http://docs.mongodb.org/manual/reference/operator/update/positional/#upsert

编辑:作为某种风格,当与 MongoDB 的 Jira https://jira.mongodb.org/browse/SERVER-10711[= 中的 $setOnInsert 运算符结合时,似乎有一个开放的功能请求来支持这种特殊类型的更新12=]