Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to remove items from a Mongodb collection based on the lack of a specific key?

As the title says, I’m trying to remove items from a collection based on the lack of a specific key.
Is there a nice way to do this?

For example, in the set below, I want to delete all records that DO NOT have an "updated" key, such as the 2nd item which only has a "created" key but not a "updated" key:

{
  "_id": {"$oid":"63fdd6becfa52a984f0a0e3a"},
  "name": "Foo",
  "created": {"$date":{"$numberLong":"1677579966215"}},
  "updated": {"$date":{"$numberLong":"1677579966547"}},
},
{
  "_id": {"$oid":"63fdd778cfa52a984f0a0e3b"},
  "name": "Bar",
  "created": {"$date":{"$numberLong":"1677580152867"}},
},

...

{
  "_id": {"$oid":"63fdd785cfa52a984f0a0e3e"},
  "name": "Baz",
  "created": {"$date":{"$numberLong":"1677580165073"}},
  "updated": {"$date":{"$numberLong":"1677580165754"}},
}

Is there a nice way to achieve this or do I have to do it one record at a time by using find() to extract the entire collection and then manually loop through each record one by one and apply deleteOne() to each matching record?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can use remove function with $exists, like this:

db.collection.remove({
  updated: {
    $exists: false
  }
})
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading