MongoDB – Usefull PHP queries

Currently I am playing around with MongoDB. Most of the topics regarding MongoDB are quite straight forward. However, sometimes I needed more complex stuff and was not able to find it or it was not documented well. So in this topic I’ll add usefull queries which helped me while developing my application.


Decrease a field

$myCollection->update(array('_id' => new MongoId($myId)),
array('$inc' => array('item.inStock' => -1)
));

Note: the negative value (-1) of the ‘item.inStock’ field.

Increment / decrease multiple fields at once

$myCollection->update(array('_id' => new MongoId($myId)),
array('$inc' => array(
'item.inStock' => -1,
'item.sold' => 1)
));

Return specific fields

$myCollection->findOne(array('_id' => new MongoId($id)), array('colors'));

This will get one item from the database with the given $id. The result will be the unique mongoId and the ‘colors’ field. So not only the expected ‘colors’ field. Other fields are not returned.

‘Not in’

$query = array(
			"_id" => array('$nin' => $ninArray),
			"item.inStock" => array('$gt' => 0)
		);
$offerCollection->find($query);		

This examples will return all items which id is not in the $ninArray and item.inStock > 1

Leave a Reply

 

 

 

You can use these HTML tags

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>