开发者

Mongodb and PHP: how to query nested arrays without using the key name

I'm probably missing something simple here but I can't seem to find a way to build a query that will allow me to update a match in a group of nested values.

I have a document like this for a b开发者_如何学JAVAlog app I've been working on (currently uses MySQL):

array (
  '_id' => new MongoId("4bc8dcee8ba936a8101a0000"),
  'created' => '20100418-201312 +0000',
  'post-title' => 'Some Post Title',
  'post-body' => 'Blah Blah Blah Blah.',
  'post-blog-name' => 'default',
  'post-comments' => 
  array (
    0 => 
    array (
      'comment-title' => 'Test1',
      'comment-body' => 'asdf1',
      'created' => '20100418-214512 +0000',
      'owner' => 'User1',
    ),
    1 => 
    array (
      'comment-title' => 'Test2',
      'comment-body' => 'asdf2',
      'created' => '20100418-214512 +0000',
      'owner' => 'User2',
    ),
  ),
  'owner' => 'zach',
  'updated' => '20100418-201312 +0000',
)

I'd like to be able to build a query that can search 'comment-title' for a match and then allow me to update/change/delete data as needed.

Obviously I can perform an update using a query which includes the key value. Something like this works:

$collection->update(
    array("post-comments.0.comment-title" => $_POST['comment-title']),
    array('$set' => array('entries.0' => array('comment-title' => $_POST['comment-title'], 'comment-body' => $_POST['comment-body'], 'owner' => $_SESSION['username'], 'updated' => gmdate('Ymd\-His O')))));

But I expect I'm missing something that would allow me to leave out the key and still be able to match one of the nested arrays based on a value (in this example the 'comment-title').

Anyway, sorry, this probably isn't the best example and I probably will end up using the keys in comments to identify them (comment #) but since nesting and creating rather complex objects seem to be a few of Mongodbs strong points I'm just hoping someone can point out what it is I might be missing.

A query to remove or update all comments by a specific user (say a user the blog author just black-listed) might be a better example. I'm not sure how I'd do this short of pulling out the entire document and then iterating through the nested arrays using PHP.


try ... notice I removed the "key"

$collection->update(array("post-comments.comment-title" ...

Cheers!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜