user3278325
user3278325

Reputation: 381

how to write (or) update in MongoDB Update Query

When I update a relation database using Hibernate, I issue a statement as follows:

Query query = getSession().createQuery(
    "update Users set isLocked = 0 where userId = :userID"
);
query.setParameter("userID", userID);

How would I do the same thing with a collection in MongoDB?

Upvotes: 0

Views: 240

Answers (2)

pgregory
pgregory

Reputation: 2093

This is an example with native mongodb-java-driver:

DBCollection coll = db.getCollection("Users"); //db is connection instance
DBObject search = new BasicDBObject("userId", userId);
DBObject data = new BasicDBObject("$set", new BasicDBObject("isLocked", 0));
coll.update(search,data);

Upvotes: 1

Mzzl
Mzzl

Reputation: 4126

I like Spring data mongodb for this purpose. A simple example of the syntax:

public User findUserByUsernameAndPassword(String userName, String encodedPassword) {
    return mongoTemplate.findOne(
            query(where("userName").is(userName).and("encodedPassword").is(encodedPassword)), User.class);
}

Upvotes: 0

Related Questions