Java 如何更新mongo db中的字段(如果不存在),如果存在,则更新其他字段
在My scenerio中,用户可以按如下所示的组合提供输入:Java 如何更新mongo db中的字段(如果不存在),如果存在,则更新其他字段,java,database,mongodb,spring-boot,mongotemplate,Java,Database,Mongodb,Spring Boot,Mongotemplate,在My scenerio中,用户可以按如下所示的组合提供输入: 1. id , status -- This will simply check id and will update the status 2. id , externalId, status -- i. Here If externalId is not present then will add externalId and also update the status ii. If external
1. id , status -- This will simply check id and will update the status
2. id , externalId, status --
i. Here If externalId is not present then will add externalId and also update the status
ii. If externalId is present then will check both id & externalId and will update status
3. externalId, status -- Here will simpley check the externalId and will update the status.
我们可以在一个查询中执行此所有操作吗
示例如下:
在DB中,我第一次会有这样的文档
{
"id": "1",
"status": "A",
}
{
"id": "1",
"externalId": "xyz",
"status": "E",
}
id=1
和status=B
,则只需添加一个id
标准。并将状态更改为B。db将按如下方式保存文档id=1
和externalid='xyz'
和status=C
,则文档将如下所示externalid='xyz'
和status=D
,则文档将如下所示id=1
和externalid='xyz'
和status=E
,则文档将如下所示
{
"id": "1",
"status": "A",
}
{
"id": "1",
"externalId": "xyz",
"status": "E",
}
5.但如果用户同时输入id=1
和externalId='pqr'
和status=F
,则文档不应将externalId更新为pqr
,也不应将状态更改为F
{
"id": "1",
"externalId": "xyz",
"status": "E",
}
This is previous document , because it is not updated
我可以使用java代码来实现这一点。但仅在查询中无法做到这一点
Query query = new Query();
Criteria criteria = new Criteria();
if(StringUtils.isNotBlank(id)) {
criteria.and("_id").is(id);
}
if(StringUtils.isNotBlank(externalId)) {
criteria.and("externalId").is(externalId);
}
query.addCriteria(criteria);
但当输入中给出两个ID时,此查询失败。我的要求是,如果两个id都给定了,那么如果externalId不存在,它应该在db中更新。我认为在一个更新查询中执行所有条件不是一个好主意,您只需执行,选择查询输入
id
,然后检查代码中的所有条件,根据条件进行更新查询。确定。谢谢你,turivishal。我在想,与仅更新相比,获取和更新将花费更多的时间。但如果这不好,那么我将使用get,应用条件,然后更新。Hi@turivishal您能为链接中的问题提供帮助吗:
Query query = new Query();
Criteria criteria = new Criteria();
if(StringUtils.isNotBlank(id)) {
criteria.and("_id").is(id);
}
if(StringUtils.isNotBlank(externalId)) {
criteria.and("externalId").is(externalId);
}
query.addCriteria(criteria);