Question about query

{ "_id" : ObjectId("61d6526cab5208fab93226a7"), "name" : "Albert Twostone", "age" : 68, "hobbies" : [ "sports", "cooking" ] }
{ "_id" : ObjectId("61d6526cab5208fab93226a8"), "name" : "Gordon Black", "age" : 38, "hobbies" : "sports" }
{ "_id" : ObjectId("61d652653b5208fab93226a8"), "name" : "Wayne Rooney", "age" : 28, "hobbies" : ["sports"] }

look 3 documents, and key hobbies.

my question is

  1. how can i get only Gordon Black??
  2. how can i get only Wayne Rooney or Albert Twostone??

i think 2. can be solved by using hobbies : {$size : 1} or hobbies : {$size : 2}
what about 1.???

find({hobbies : “sports”}) lead to 3 documents.
pleaase help me.

To get only the one with a string you also want to check for the type to ensure it is not an array. It is done, the usual way, with

{ "hobbies" : { $not : { $type : "array" } } }

But you would need to use explicit $and. Personnally I prefer:

// hobbies.0 is the first element of the array hobbies, so if it does not
// exist then hobbies is an empty array or is not an array
{ "hobbies.0" : { $exists : false } }

which is shorter and does not require explicit $and. Try

find( { "hobbies" : "sports" , "hobbies.0" : { $exists : false } } )
1 Like

Thank you very much.
Very helpful for me!

1 Like

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.