I am building a social network in mongo db. Following is the structure of document in the groups collection. It represents each social group present in the system. Users are a part of this group which is represented by the 'members' property which is an array if json objects.
{
"group_name":"my group",
"members": [
{
"user_id": ObjectId("4e29341986ba75dc14000000"),
"joined": ISODate("2011-07-26T11:46:49.0Z")
},
{
"user_id": ObjectId("4e2ea94286ba75f81500000e"),
"joined": ISODate("2011-07-26T11:47:55.0Z")
},
{
"user_id": ObjectId("4e2eaa0786ba75e815000003"),
"joined": ISODate("2011-07-26T11:55:22.0Z")
},
{
"user_id": ObjectId("4e2eab7f86ba75ec1500000a"),
"joined": ISODate("2011-07-26T11:57:44.0Z")
},
{
"user_id": ObjectId("4e2eac3586ba75dc15000000"),
"joined": ISODate("2011-07-26T12:00:57.0Z")
},
{
"user_id": ObjectId("4e2eacae86ba75dc15000004"),
"joined": ISODate("2011-07-26T12:02:43.0Z")
},
{
"user_id": ObjectId("4e2eadbb86ba75ec1500000c"),
"joined": ISODate("2011-07-26T12:07:01.0Z")
}
]
The problem I am facing is how do I check if a user belongs to a certain group. This is what I came up with but it doesn't seem to work. Please help.
$criteria = array(
'_id' => new MongoId($group_id),
'members' => array('user_id' => new MongoId($user_id))
);
return $collection->find($criteria);