How to do upsert using jongo?

那年仲夏 提交于 2019-12-08 15:14:35

Considering having a user with an already loaded googleId (passed google auth), and I'd like to upsert it to mongoDB, using Jongo:

// Init
MongoClient mongoClient = new MongoClient("localhost", 27017);
DB db = mongoClient.getDB(DB_NAME);
Jongo jongo = new Jongo(db);
org.jongo.MongoCollection collectionJongo = jongo.getCollection(USER_COLLECTION_NAME);

// Upsert
String query = "{googleId: {$eq: #}}";
collectionJongo.update(query, user.googleId)
        .upsert()
        .with(user);
user = collectionJongo.find(query, user.googleId).as(User.class).next();
// Works only on insert. On update, the upsertedId is null.
//user._id = ((ObjectId) writeResult.getUpsertedId()).toHexString();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!