Can I update a document I have already found without making another query?

I’m using Node native language.

In my code, I have already found a user document with user = collection('user').findOne({...}).

I want to update a field on this user document.

I know the updateOne() function, however that takes a query as opposed to a document object, which has to perform another query.

I was expecting something like:

user.update({...})
or
collection('user').updateOne(user, {...})

Do this mean if I want to perform an update on a document I have already found with findOne(), I need to perform another query?

The updateOne method takes a filter and an update document as parameters. But, the update operation on a single document is atomic.

Lets take this example, where you have already queried a user. The user document has the unique _id field (or some other unique identifier for the user), and use this as the update operation’s query (or filter).

Assume you have a user document like this:

{ 
  _id: 1, 
  name: "John", 
  email: "john@example.com", 
  country: "Australia" 
}

You query it by email:

let user_john = db.users.findOne( { email: "john@example.com" } }

Now, update the user to add a new field called as phone.

db.users.updateOne( 
  { _id: user_john._id }, 
  { $set: { phone: "123-456-7890" } }
 )

The above update operation adds the new field to the user with _id: 1.

  • { _id: user_john._id } is the query filter, this lets the update happen on the specific document.
  • { $set: { phone: "123-456-7890" } } is the update.
1 Like