Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How To Query A Dictionary on MongoDB

I have the following class

public class Group {
  [BsonId]
  public ObjectID _id {get; set;}
  [BsonElement("Me")]
  public Members Dictionary<ObjectId, UserGroupProperties> Members {get; set;}
}

How Do I query on Members property? Where Memebres.ObjectId == objectid? Thanks!

like image 440
elranu Avatar asked Dec 04 '25 01:12

elranu


1 Answers

MongoDB has a "dot notation" for reaching into sub-objects or arrays.

Normally, the query will look something like the following:

Query.EQ("Me._id", objectid)

And will find data of this structure:

{ 
  _id: ObjectId(),
  me: [
        { _id: ObjectId(): { UserGroupProperties } },
        { _id: ObjectId(): { other UserGroupProperties } }
      ]
}

However, it looks like your data structure is a little different. Is your data like the following?

{ 
  _id: ObjectId(),
  me: {
        ObjectId(): { UserGroupProperties },
        ObjectId(): { other UserGroupProperties }
      }
}

If so, then you're looking for the existence of "me.objectid". Which is different.

The big thing to note here is that MongoDB will return the entire matched document. So if you're looking for a single UserGroupProperties your query is going to return the entire Group.

like image 60
Gates VP Avatar answered Dec 06 '25 22:12

Gates VP



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!