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?

>Solution :

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

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

Leave a Reply