How to insert a document if certain key not exists in mongodb - php

I've been looking at questions like mongodb: insert if not exists , which gives pointers to "upsert" behavior.
However I expect only to create object if certain key is not found, i.e.
if ( $collection->findOne ( array ('key'=>'the_key') ) == NULL ) {
$collection->insert ( array ('key' => 'the_key', 'content' => 'the_content' );
} else {
// else don't touch it, so upsert would not fit.
}
I'm using PHP mongodb driver for this.
The above code is just the demonstration for my purpose. However there lacks the atomicity required. How this should be achieved?
Thanks in advance!

As you should define a unique index for this key anyway, you could also use it to prevent inserting objects with such a key multiple times. Have a look at the index documentation over at:
http://www.mongodb.org/display/DOCS/Indexes#Indexes-UniqueIndexes
Not a nice solution -- imo -- but the only one i can think of, if you do not want to do the update or can not do it for whatever reason. Keep in mind, that you will probably receive an error when trying to insert a object with this same key again, which you would have to handle.

Related

How to get around PHP array forcing a key

I have a very simple array where I want to be able to add settings as simple as possible. In my case, if I don't need a second value, I don't need to add it.
Code
$settings = [
'my_string',
'my_array' => 'hello'
];
print_r($settings);
Result
The problem with my approach is that my_string is seen as a value and the key 0 is added.
Array
(
[0] => my_string
[my_array] => hello
)
I could check if the key is a number and in that case figure out that I don't use a second value.
Is there a better approach?
I'm aware of that I can use multiple nested arrays but then simplicity is gone.
The way you've written it, you wouldn't be able to access the value 'my_string' without some kind of key. There is always a key for any value, and if you don't specify values, PHP generates them as though they were indices in an actual array (PHP 'arrays' are actually dictionaries/maps/etc. that have default behavior in the absence of a specified key).
$settings = [
'name' => 'my_string',
'my_array' => 'hello'
];
If you don't want to use $settings[0] -- and I wouldn't want to either -- you should probably decide on a name for whatever 'my_string' is supposed to be and use that as its key.

UpdateAttributes does not work

I have a problem with UpdateAttributes, it seem to not work for me.
When I issue:
$ret = $sphinx->UpdateAttributes ( "products", array ("status"), array(506607786 => array(10)) );
it returns 1, but search still returns status as old value for this.
When I try
$ret = $sphinx->UpdateAttributes ( "products", array ("status", "image_id"), array(506607786 => array(10, 6666)) );
it returns 0 (false)
Does this function even work ?
Ok I have found (sphinx docs are ugly) that when issuing updateAtrributes() from PHP app then I will not see the results in search command line. However one problem still
exist - I'm not able to update 2 attributes in one updateAtrributes() - seperatly they are fine - any clues why ?
When UpdateAttributes returns 0 (not false) it does not mean it didn't work, what it means is it didn't find anything to update, basically no updates commited. A return of -1 actually means this function did not work.
Make sure that 506607786 is actually an id in your Sphinx index and that products is the name of your index.
To make the question more helpful you can provide an example row from your table, preferrably the one used in this function defined as 506607786. You cna also provide a full set of your code to make it easier.
As a side note: UpdateAttributes does not act like a realtime index. You will need to filter on these attributes specifically in your query in order for sphinx to take their new values into consideration.

MongoDB - Is it possible to query by associative array key?

I need to store some data that is essentially just an array of key-value pairs of date/ints, where the dates will always be unique.
I'd like to be able to store it like an associative array:
array(
"2012-02-26" => 5,
"2012-02-27" => 2,
"2012-02-28" => 17,
"2012-02-29" => 4
)
but I also need to be able to query the dates (ie. get everything where date > 2012-02-27), and so suspect that I'll need to use a schema more like:
array(
array("date"=>"2012-02-26", "value"=>5),
array("date"=>"2012-02-27", "value"=>2),
array("date"=>"2012-02-28", "value"=>17),
array("date"=>"2012-02-29", "value"=>4),
)
Obviously the former is much cleaner and more concise, but will I be able to query it in the way that I am wanting, and if not are there any other schemas that may be more suitable?
You've described two methods, let me break them down.
Method #1 - Associative Array
The key tool for querying by "associative array" is the $exists operator. Here are details on the operator.
So you can definitely run a query like the following:
db.coll.find( { $exists: { 'field.2012-02-27' } } );
Based on your description you are looking for range queries which does not match up well with the $exists operator. The "associative array" version is also difficult to index.
Method #2 - Array of objects
This definitely has better querying functionality:
db.coll.find( { 'field.date': { $gt: '2012-02-27' } } );
It can also be indexed
db.coll.ensureIndex( { 'field.date': 1 } );
However, there is a trade-off on updating. If you want to increment the value for a specific date you have to use this unwieldy $ positional operator. This works for an array of objects, but it fails for anything with further nesting.
Other issues
One issue with either of these methods is the long-term growth of data. As you expand the object size it will take more space on disk and in memory. If you have an object with two years worth of data that entire array of 700 items will need to be in memory for you to update data for today. This may not be an issue for your specific data, but it should be considered.
In the same vein, MongoDB queries always return the top-level object. Again, if you have an array of 700 items, you will get all of them for each document that matches. There are ways to filter out the fields that are returned, but they don't work for "arrays of objects".

How to Use MongoID As Key in Update Query

I've created a query in PHP which is used to add a user to an array. Right now it checks to see if they exist and if they don't it adds them to the array. Here's the full code:
try{ $this->users_db->update(
array(
'_id' => new MongoId($user_id) ,
new MongoId( $group_id ) => array('$nin'=>USER_GROUPS)
),
array(
'$push' => array(USER_GROUPS => array( GROUP_ID => new MongoId($group_id), USER_GROUP_NOTIFY => true ) )
)
); }
catch(Exception $e)
{ return false; }
The problem is that PHP is giving me the Warning "Illegal offset type" since MongoId() is an object and objects can't be used as keys in arrays. Any ideas about how to work around this?
I think you have the order of your "arguments" to $nin backwards. Your query is equivalent to something like this in the mongo shell:
db.users.update({_id: ObjectId("..."), ObjectId("..."): {$nin: ["user_groups"]}}, ...);
Which reads like English, left to right, when pronouncing "$nin" as "is not in". A more correct, by MongoDB's grammar, pronunciation is "does not contain", so your query is actually saying something like "where some ObjectId does not contain this array", which makes little sense when said out loud.
With that in mind, your query should look like:
db.users.update({_id: ObjectId("..."), user_groups: {$nin: [ObjectId("...")]}}, ...);
When running into issues like this with updates or removes, it's often useful to try the query spec portion as an argument to find() or findOne() to determine what's wrong there. Once you can find the document you want to update, you can re-write as a call to update(), remove(), etc.
Also, you should be aware that there is an $addToSet atomic operator which performs this sort of check for you atomically in the database. You could try:
db.users.update({_id: ObjectId("...")}, {$addToSet: {user_groups: ObjectId("...")}});
EDIT: For future reference to OP and other askers, see mongodb docs on query operators and mongodb docs on update operators.

Provide my own value for mongodb $id index with PHP

I want to insert my own unique value into the mongodb $id field
I already have a unique key and I don't want to take up extra space with yet another index.
How can I do this with the PHP API?
$collection->save(array('_id' => new MongoId('my_mongo_id'), 'foo' => 'bar'));
The docs above explain this in a general way, but to give you a PHP-specific example you simply set the _id value to your generated id when you create the document:
<?php
$mongo = new Mongo();
$collection = $mongo->dbName->collectionName;
$id = your_id_generator(); // I assume you have one
$collection->save(array('_id' => $id, 'foo' => 'bar'));
print_r( $collection->findOne(array('_id' => $id)) );
check this link
http://www.mongodb.org/display/DOCS/Indexes#Indexes-UniqueIndexes
As long as you can guarantee uniqueness, you're not constrained to using the default "_id" MongoDB supplies.
Therefore, it's down to you how you generate this number. If you'd like to store this number inside MongoDB, then you could store it in a separate collection and increment it for every new URL required.
Incrementing a field is achieved by using the $inc verb, or you may want to take a look at how MongoDB can atomically update or increment a value.
Unique IDs with mongodb
I wrote a class to generate auto-increment values for Mongo in php
You can check out my project on gitgub https://github.com/snytkine/LampCMS
and look for /lib/Lampcms/MongoIncrementor class.
It basically keeps track of per-collection "nextValue" value
Works great for me, maybe it will work for you too.
Also feel free to examine my classes, I use MongoDB and php heavily, maybe you can learn something from the code or maybe can show/teach me some cool mongo/php code.
Hope this helps.

Categories