Mongodb 仅在值唯一时插入,否则更新 - 在 node.js 中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22849527/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Mongodb only insert if value is unique, else update - in node.js
提问by DeaIss
I've started developing an app recently and have finally got my node.js server communicating with my mongodb database.
我最近开始开发一个应用程序,终于让我的 node.js 服务器与我的 mongodb 数据库进行通信。
I want to insert a bunch a JSON objects that look something like this:
我想插入一堆看起来像这样的 JSON 对象:
{
'Username': 'Bob',
'longitude': '58.3',
'latitude': '0.3'
}
If this Object is inserted into myCollection, and then I try to insert an object again with the Username Bob, but with different coordinates, I want the latest 'Username': 'Bob' object to replace the earlier one. There can only be one object in myCollection with the 'Username': 'Bob' basically.
如果将此对象插入到 myCollection 中,然后我尝试再次使用用户名 Bob 插入一个对象,但使用不同的坐标,我希望最新的 'Username': 'Bob' 对象替换较早的对象。myCollection 中只能有一个带有“用户名”的对象:基本上是“Bob”。
If this was a relational database I would make Bob a primary key or something, but I was wondering what the best way to do this with mongoDb would be. Should I use the update+upsert method? I tried that and it didn't seem to work!
如果这是一个关系数据库,我会让 Bob 成为主键或其他东西,但我想知道用 mongoDb 做到这一点的最佳方法是什么。我应该使用 update+upsert 方法吗?我试过了,它似乎没有用!
Apologies if this seems like a silly question, but I am still new to all of this.
如果这似乎是一个愚蠢的问题,我深表歉意,但我对这一切仍然陌生。
回答by Anand Jayabalan
Yes, a simple update
query with the upsert
option should satisfy your use case:
是的,update
带有该upsert
选项的简单查询应该可以满足您的用例:
db.collection.update(
{username:"Bob"},
{$set:{'longitude': '58.3', 'latitude': '0.3'}},
{ upsert: true}
)
When you run the above query the first time (i.e., Bob doesn't exist in the collection), a new document is created. But when you run it the second time with new values for lat/long, the existing document is updated with the new lat/long values.
当您第一次运行上述查询时(即,集合中不存在 Bob),将创建一个新文档。但是,当您使用新的经纬度值第二次运行它时,现有文档将使用新的经纬度值进行更新。
You can also create a unique index
on the username
field to prevent multiple records for 'Bob' from being created even accidentally:
您还可以unique index
在username
字段上创建一个,以防止意外创建“Bob”的多个记录:
db.collection.ensureIndex( { "username": 1 }, { unique: true } )
EDIT:
编辑:
db.collection.ensureIndex()
is now deprecated and is an alias for db.collection.createIndex()
. So, use db.collection.createIndex()
for creating indexes
db.collection.ensureIndex()
现在已弃用,是db.collection.createIndex()
. 所以,db.collection.createIndex()
用于创建索引