---
title: "mongeDB 存在数据则更新没有数据则插入"
author: "umbrellall1"
date: "2019-11-12T15:06:38Z"
tags: ["Java", "MongoDB"]
categories: ["编程语言"]
slug: "mongedb"
draft: false
lastmod: "2019-11-12T15:06:38Z"
id: 2509878
url: "https://umbrellall1.iteye.com/blog/2509878"
---

```java

Document doc2 = new Document();
        	doc2.append("$set",doc);
        	collection.updateOne(filter, doc2,new UpdateOptions().upsert(true));

```

将doc 外层包裹并且设置$set 就可以保留原始数据情况下 新增字段
new UpdateOptions().upsert(true) 默认false  ，true 的情况下有则更新，无则插入原则