How to do upsert using jongo?

吃可爱长大的小学妹 提交于 2019-12-23 04:06:30

问题


I have a users table/collection and would like to upsert a user - update a user if exists or add a new one if still not exists. Structure below.

By "exists", I mean having some external ID. In this case, googleId.

How can I do it using Jongo library? Thanks.

public class User {
    public String _id;
    public String email;
    public String givenName;
    public String familyName;
    public String googleId;
}

回答1:


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();


来源:https://stackoverflow.com/questions/41103427/how-to-do-upsert-using-jongo

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!