英文:
Finding duplicate entries in Spring Boot MongoDB?
问题
我对Spring Boot还不熟悉,但我一直在尝试找出如何在MongoDB中查找重复项并进行报告。
例如,每个条目都有一个用于数据库的_id,一个条目名称和一个条码。这三者都需要是唯一标识符,可以进行搜索。
举个例子,用户一段时间前创建了100个条目,但出于某种原因忘记了他们创建了一个条码为255的“Jaffa”条目。
尽管应用程序有一个搜索功能,但出于某种原因,用户忽略了它,无法用传统的方式找到它,因此尝试创建一个具有与上述相同条码的新的“Jaffa”条目。
我该如何让我的应用程序浏览数据库,并报告条目是否已经存在,如果不存在则可以使用名称或条码进行创建呢?
谢谢
英文:
I'm new to Spring Boot and I've been trying to find out how you go about finding duplicates in MongoDB and reporting it.
For example each entry has an _id for database use, an entry name, and a barcode. All three of these need to be unique identifiers which can be searched.
For example. A user has created 100 entries a while back and for some reason has forgotten they've created a "Jaffa" entry with a barcode of 255.
Despite the app having a search function, the user neglects using it for what ever reason and they cannot find it the old fashioned way so tries to create a new "Jaffa" entry with the same barcode as above.
How do I get my app to look through the DB and report if the entry already exists or create otherwise either using the name or the barcode?
Thanks
答案1
得分: 0
你可以使用设置为true的upsert选项来进行更新。当你使用任意名称创建一个newEntry时,如果它已经存在,那么它将会更新现有的条目数据;如果不存在,则在没有任何文档与查询条件匹配时创建一个新文档。
这里是db.collection.update(query, update, options)。
例如:
db.collection.update({entryName: newEntry}, {$set: {entryName: newEntry, barcode: newBarCode}}, {upsert: true})
英文:
You can use update with upsert option set to true. When you create a newEntry with whatever name, if it exists then it will update the existing entry data and if it doesn't exist then it creates a new document when no document matches the query criteria.
Here it is db.collection.update(query, update, options).
For ex:
db.collection.update({entryName: newEntry}, {$set: {entryName: newEntry: barcode: newBarCode}}, {upsert : true})
专注分享java语言的经验与见解,让所有开发者获益!
评论