Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find documents that contains specific field

I have documents like this in my mongodb

{ "_id" : ObjectId("5342b21c0b01a29f6a000b4b"), "vec" : { "1" : 0.97, "4" : 0.11, "5" : 0.07 } }
{ "_id" : ObjectId("5342b1b90b01a29f6a000b32"), "vec" : { "1" : 0.84, "9" : 0.06 } }
{ "_id" : ObjectId("5342b1da67fbc7a16a000b52"), "vec" : { "2" : 0.71, "4" : 0.57, "8" : 0.52, "9" : 0.19 } }
{ "_id" : ObjectId("5342b1f6df2a17a06a000b6b"), "vec" : { "5" : 0.96, "6" : 0.35, "9" : 0.12 } }

and if I want to select only docs which contains "4" in vec field I can do this:

db.collection.find({"vec.4" : {$gte : 0}})

but using this code I automatically assume that all values are greater than zero. What if not - how to select documents with field "4" regardless of their value?

like image 706
bartektartanus Avatar asked Dec 05 '25 03:12

bartektartanus


1 Answers

You can use $exists for that:

db.collection.find({"vec.4" : {$exists : true}})
like image 172
JohnnyHK Avatar answered Dec 09 '25 21:12

JohnnyHK



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!