Search code examples
phpmongodbphp-mongodbdbrefreference-manual

MongoDB - PHP manual references approach suitability


MongoDB newbie here. I'm having the first approach on references, and my main doubt is if i'am using the appropriate strategy(manual references) for my situation.

Working on 2 collections(user, message) in the same db, lets make an example of a document stored in user collection:

array (
  '_id' => new MongoId("5231817277758e660c7202c4"),
  'uname' => 'pluto',
  'pwd' => new MongoInt32(1234567),
  'email' => '[email protected]',
  'phone_home' => new MongoInt64(23409238),
  'phone_work' => new MongoInt64(54389724),
  'phone_mobile' => new MongoInt64(9823422),
  'visible' => new MongoInt32(1),
)

and an example of a document stored in message collection (sent FROM an other user TO the user above 'pluto'):

array (
  '_id' => new MongoId("524358102660b2c70b8b4567"),
  'from_uid' => '5231817277758e660c7202d7',
  'to_uid' => '5231817277758e660c7202c4',
  'object' => 'mongo manual Ref',
  'content' => 'is that the correct approach?',
  'datetime' => '2013-09-25 23:39:28',
)

The user logged in ('pluto') can see all the messages he received from other users but, i don't wat to print the 'from_uid' value, i want to replace it with the username of the sender.

My main doubt is if manual references is the right approach for this scenario, because with this technique(if i havn't miss understood everything), print a list of message would involve:

  1. the 'query' for print the list of messages
  2. an other 'query' for retrieve the username from the other collection, for each messages. Also if a user have received 1000 messages, this approach will have to run 1001 query??

My secondary doubt is if there is a way for directly merge or replace the result of two cursors


Solution

  • Given your use case it would probably be ok to duplicate a little bit of data and store some of the necessary fields about the sending user as an embedded document - in this case, the username.

    array (
      '_id' => new MongoId("524358102660b2c70b8b4567"),
      'from_user' => array(
         'uid'   => '5231817277758e660c7202d7',
         'uname' => 'mars'
       ),
      'to_uid'   => '5231817277758e660c7202c4',
      'object'   => 'mongo manual Ref',
      'content'  => 'is that the correct approach?',
      'datetime' => '2013-09-25 23:39:28',
    )
    

    This approach means that when you query for messages to a user ( in which you already know the to_uid), you get all of the messages with the correct id to the from_user, but also already have their username to display.

    Now, instead of querying 1000+ times, you only need to query when there is more information needed about a user - such as fetching their profile, etc...