1

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);

2 Answers 2

4

try with the following code:

$criteria = array(
        '_id' => new MongoId($group_id),
        'members.user_id' => new MongoId($user_id))
    );


return $collection->find($criteria);

see http://www.mongodb.org/display/DOCS/Dot+Notation+%28Reaching+into+Objects%29

Sign up to request clarification or add additional context in comments.

Comments

3

Use the $elemMatch operator.

In Mongo shell, you'd do:

> criteria = { 
...   "_id" : ObjectId("group_id"), 
...   "members" : {
...      $elemMatch : {
...         "user_id" : ObjectId("user_id")
...      }
...   }
...}
> db.groups.find(criteria);

It will search the groups collection for an entry for which a members object has a user_id of ObjectId("user_id").

Haven't tested it in PHP, but since the structure is the same, this should do it:

$criteria = array(
    '_id' => new MongoId($group_id),
    'members' => array(
       '$elemMatch' => array(
           'user_id' => new MongoId($user_id)
       )
    )
);

return $collection->find($criteria);

Tip: Remove the _id clause completely and you can find out to which groups the user belong (instead of querying each one separately).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.