1

Assume, that I have bunch of entries in a document:

db.document

and some of them doesn't have some key, let's say name. So we have two types of entries - with and without name.

{ "_id" : ObjectId("4dea81a8bd2bb0323800002d"), "fetched_at" : ISODate("2013-08-02T17:41:30Z"), "keyword" : "110770", "name" : "SOME NAME" }

{ "_id" : ObjectId("4dea81a8bd2bb0323800002a"), "fetched_at" : ISODate("2013-08-02T17:44:17Z"), "keyword" : "125176" }

I want to remove all entries without name property, because it makes my database incosistent. How can I do that? I tried with null and undefined but it doesn't works.

Community
  • 1
  • 1
ciembor
  • 7,189
  • 13
  • 59
  • 100

2 Answers2

3

it's possible using $exists:

db.document.remove( { name : { $exists : false } } );
Jetson John
  • 3,759
  • 8
  • 39
  • 53
0
db.document.remove( { name : null } )

should work too. Example:

> db.document.insert({"fetched_at" : ISODate("2013-08-02T17:41:30Z"), "keyword" : "110770", "name" : "SOME NAME"})
> db.document.insert({"fetched_at" : ISODate("2013-08-02T17:44:17Z"), "keyword" : "125176" })
> db.document.insert({"fetched_at" : ISODate("2013-08-02T17:44:17Z"), "keyword" : "125176" })
> db.document.find().size()
3
> db.document.remove({name:null})
> db.document.find().size()
1
> db.document.find().pretty()
{
    "_id" : ObjectId("520eac7e5d0ee1aa8515a550"),
    "fetched_at" : ISODate("2013-08-02T17:41:30Z"),
    "keyword" : "110770",
    "name" : "SOME NAME"
}
sil3
  • 63
  • 1
  • 4