MongoDB: insert record if it doesn't exist, ignore if it does

I have a series of MongoDB records like: `{"name":"Bob", "gpa":4}` `{"name":"Sarah", "gpa":3}` I will encounter various additional records that may or may not pertain to the same people. I want to accept them if they're new people, and _not_ update them if they're people we've seen before. So if I get `{"name":"Jim", "gpa":2}`, I want to accept that as-is. If I get `{"name":"Sarah", "gpa":4}` (different GPA value), I want to just ignore it. This doesn't seem to be the logic of either `update` with "upsert" set to yes, or of `findAndModify` with "upsert." https://stackoverflow.com/a/3260290/514757 suggests a way (unique index on the first field, insert record, immediately update the second field) but it's a few years old and I wonder if there isn't a better way now to do this in a single step. EDIT: The accepted answer seems great, but it's not working for me! First, I created the index (this is with the Java driver): nameIndex.put("name", 1); nameIndex.put("unique", true); queue.ensureIndex(nameIndex); I can see from the command line that the index exists and is unique. Then, an item is inserted: DBObject person = new BasicDBObject(); person.put("name", "Bob"); person.put("score", 200000); queue.insert(person); Later, the item with the highest score has its score reduced to zero: BasicDBObject reset = new BasicDBObject(); reset.put("$set", new BasicDBObject("score", 0)); DBObject dbObj = queue.findAndModify(null, new BasicDBObject("score", -1), reset); All of this works just as intended! But, later, the same name may be found again, with a new score. When this last bit of code runs, a new item is created with a different score, which is exactly what I don't want: BasicDBObject queueable = new BasicDBObject(); queueable.put("name", "Could be Bob again, could be someone new"); queueable.put("score", 1234); queue.insert(queueable); If I search for Bob, I find: { "_id" : ObjectId("4f5e865ad6d09315326ea0f0"), "score" : 0, "name" : "Bob" } { "_id" : ObjectId("4f5e8691d6d09315326ea190"), "name" : "Bob", "score" : 886 } A second record has been created, with the higher score again. Does the order of the fields matter? It doesn't seem like it should, and I don't know how to control that.
the order of fields does not matter. fixing your ensureIndex call per the answer from @tripvolpe below should solve your problem. please accept trip's answer if it does.

以上就是MongoDB: insert record if it doesn't exist, ignore if it does的详细内容,更多请关注web前端其它相关文章!

赞(0) 打赏
未经允许不得转载:web前端首页 » JavaScript 答疑

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址

前端开发相关广告投放 更专业 更精准

联系我们

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信扫一扫打赏