I made a wrong update query in MongoDB

I have updated a couple of documents via a wrong query. My query was very generic and have updated a couple of documents. How do I see the ones I’ve updated via the query I have ran?

A general update statement takes the form, for example, in the following update operation all people with last name “Smith” have their country changed to “UK”:

  { lastName: "Smith" }, 
  { $set: { country: "UK" } } 

In the above query:

  • { lastName: "Smith" } is the query filter - this selects the documents that are to be updated.
  • { $set: { country: "UK" } } is the update - this modifies the field with a new value.

The query filter tells which documents are modified and the update tells what fields are updated with what data.

So, if you run a query, like the one below, it lists all the documents the previous update has changed:

db.people.find({ lastName: "Smith" })

1 Like

And, if you do not remember the query, there are some things to try. But I am not that knowledgeable this are some ideas…

logging in the operations log aka oplog

Not valid for standalones as the oplog is not there.

A capped collection that stores an ordered history of logical writes to a MongoDB database.

The oplog is found in the database local, collection oplog, you would type something like:

use local

I believe.

Check the log file

You could inspect the log file also.

Check the terminal

if you run through terminal, just uparrow and see if it is in the history of commands.

1 Like

Are you sure the update operations are written to the server logs?

1 Like

Great question! You are right, they are not.

I thought the “write” part would be there but it is not.

1 Like

Oops, they are indeed logged, I was just using findOne() on the first check.

You will see it like this:

Atlas local> db.oplog.rs.find()
    op: 'i',
    ns: 'chatApp.messages',
    ui: UUID("ec5c9f89-2f0b-4ee5-acfd-ea350fd409e1"),
    o: { _id: ObjectId("6298b40f381f656739e7f74e"), toRemove: true },
    op: 'd',
    o: { _id: ObjectId("6298b40f381f656739e7f74e") },
    prevOpTime: { ts: Timestamp({ t: 0, i: 0 }), t: Long("-1") }
    op: 'u',
    ns: 'chatApp.messages',
    o: { '$v': 2, diff: { u: { tid: 'rem' } } },

You can see “i” for insert, “d” for delete and “u” for update and the queries/body carried out :slight_smile:

For the system records, I am not fully sure, i think this depend on the LogLevel.

1 Like

Another place to look for query details is the mongosh logs. This is useful if you are using the mongosh for running your queries. The details from logs can be viewed using instructions from: Retrieve Shell Logs.

In case you are using the older mongo shell, similar logs are available.