How to do upsert using jongo?
Asked Answered
S

1

1

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;
}
Significance answered 12/12, 2016 at 14:46 Comment(0)
S
3

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();
Significance answered 12/12, 2016 at 14:51 Comment(1)
I have no idea how or why this was downvoted - Jongo is the worst documented framework I've come across, this is very helpful.Aircrewman

© 2022 - 2024 — McMap. All rights reserved.