$addToSet and $inc for updating a row - php

I'm working on a rating system. When a user rates, $inc increments the field, and addToSet adds the user_id to make sure the user only clicks rate once. I am checking if the user_id is already in the x field before updating, but that is another query which I'd rather avoid. Can I reach this purpose without having to write another query? I mean, $addToSet only adds if there is no value like that; can I instead get affected rows? Can you suggest other queries?
Thank you!
..->update(
array("_id" => $idob),
array(
'$inc' => array($type => (int) 1),
'$addToSet' => array("x" => (int) $user_id)
)
);

Ok I see the problem.
..->update(
array("_id" => $idob),
array(
'$inc' => array($type => (int) 1),
'$addToSet' => array("x" => (int) $user_id)
)
);
The problem is that you need a conditional $inc there so that it only $incs if it does add to set.
This is not possible with a unique index since unique indexes work from the root of the document atm. Also you probably want to use the $inc as a form of pre-aggregation or what not.
One method could be:
update(
array('_id' => $idob, 'x' => array('$nin' => array($user_id))),
array(
'$inc' => array($type => 1),
'$push' => array('x' => (int)$user_id)
)
)
This will only do the update if that user_id does not already exist in x.

Related

Compound Indexes on MongoDB

Sorry for my english, I need help on mongodb indexes. I have a capped collection (size: 10GB) with some fields for my application logs.
Example structure: Logs[_id, userId, sum, type, time, response, request]. I have created compound index: [userId,time,type]. I get two arrays are grouped records by userId for today, where 'type' is "null" and "1". And my two query example:
$group = array(
array(
'$match' => array(
'userId' => $userId,
'time' => array(
'$gt' => date("Y-m-d")
),
'type' => array('$ne' => null)
)
),
array(
'$group' => array(
"_id" => '$userId',
"total" => array('$sum' => '$sum'),
"count" => array('$sum' => 1)
),
)
);
$results = $collections->aggregate($group);
$group = array(
array(
'$match' => array(
'userId' => $userId,
'time' => array(
'$gt' => date("Y-m-d")
),
'type' => 1
)
),
array(
'$group' => array(
"_id" => '$userId',
"count" => array('$sum' => 1)
),
)
);
$results2 = $collections->aggregate($group);
If current user has more 100000 documents on collection for today - the speed of my query is very slow (more 10 sec). Give me some advices on creating the right index, please :) Thanks.
Based on the explain that you posted, the correct index is being used (BtreeCursor), it is using only the index (i.e. it is a covered index query - indexOnly is true) and nothing is being matched (n = 0) in this case. So, that all checks out generally, though $ne as a clause in the first example is not going to be very efficient.
However the main issue based on the explain is likely the fact that the index does not appear to be fully in memory. There are 13 yields listed and the most common reason for a query like this to yield is when it has to fault to disk to page something in. Since, as mentioned previously, it is only using the index, those yields imply faults to disk for the index and hence indicate that the whole index is not in memory.
If you re-run the query immediately after this it should be faster (assuming the index can actually fit into available memory) because the index will have been paged in by the first run. If it is still slow on the second run and showing yields, then you either don't have enough memory to hold the index in memory or something else is evicting it from memory and you essentially have memory contention causing performance problems.

If column have a row=$variable and in another column on the same row=$variable2 return value 1

Sorry for confusing title. But I don't know how to explain this.(I don't speak that good English)
Here is a picture to make it alittle bit more clear:
http://img823.imageshack.us/img823/8812/edxt.png
If pic_name=328.jpg AND user=myhrmans return value of 1
else if you cant find value user=myhrmans return 0 for example. Anyway I can pull this off?
Thank you :)
Not sure to understand precisely what you mean, but I'm going to make an attempt.
Your query should be written somehow like this one:
SELECT user, pic_name,
IF(user = 'myhrmans' AND pic_name = '328.jpg', 1, 0) AS value
FROM yourtable
WHERE user = myhrmans;
When executed from PHP (and after fetching the values), your query will return this array:
$result = array(
0 => array(
'user' => 'myhrmans',
'pic_name' => '326.jpg',
'value' => 0
),
1 => array(
'user' => 'myhrmans',
'pic_name' => '329.jpg',
'value' => 0
),
2 => array(
'user' => 'myhrmans',
'pic_name' => '328.jpg',
'value' => 1
),
3 => array(
'user' => 'myhrmans',
'pic_name' => '319.jpg',
'value' => 0
)
);
Which, if I understood, approaches what you want.

mongodb update if a field does not exist

$db->akis->update(
array("h" => (string) $_SESSION["_id"], "m" => array('$exists' => false)),
array('$set' => array("k" => $name)),
array("multiple" => true)
);
what i did in here is, if there is an m field, do not update k. What I want to add is, "if m field exists" update i instead of k field, how can I manage this ?
thank you
I think you will need to do two separate queries here. That is just too conditional for MongoDB query parser to handle.
So you will need to put your logic into two separate queries with the second looking like:
$db->akis->update(
array("h" => (string) $_SESSION["_id"], "m" => array('$exists' => true)),
array('$set' => array("i" => $name)),
array("multiple" => true)
);
Running one after the other.

cakePHP complex find query

how do I build a find() query in cakePHP using these conditions:
Find where
MyModel.x = 1 and MyModel.y = 2 OR
MyModel.x = 1 and MyModel.y value does not exist (or is equal to empty string)
Can somebody tell me how I can go about building such find query?
I'm gonna give you some pointers, but you need to try to do this as it's very basic and it's always good to practice.
A basic find in cake is in the form of
$this->ModelName->find('all');
This in its default form does a SELECT * from model_names (convention is to have singular ModelName for plural table name - model_names)
To add conditions:
$this->ModelName->find('all', array('conditions' => array('ModelName.x' => 1));
To add AND conditions
$this->ModelName->find('all', array('conditions' => array(
'ModelName.x' => 1, 'ModelName.y' => 2
));
To add OR conditions
$this->ModelName->find('all', array('conditions' => array(
'OR' => array(
'ModelName.x' => 1, 'ModelName.y' => 2
)
));
To combine both
$this->ModelName->find('all', array('conditions' => array(
'ModelName.y is not' => null,
'OR' => array(
'ModelName.x' => 1, 'ModelName.y' => 2
)
));
// where y is not null and (x = 1 or y = 2)
http://book.cakephp.org/1.3/view/1030/Complex-Find-Conditions
(btw I'm sure there will be users giving you the exact answers, so just take my answer for your reference :) )
$this->MyModel->find('all', array('conditions' => array(
'OR' => array(
array(
'MyModel.x' => 1,
'MyModel.y' => 1
),
array(
'MyModle.x' => 1,
'OR' => array(
array('MyModel.y' => NULL),
array('MyModel.y' => '')
)
)
)
)));

cakephp OR condition

Originaly posted on cakephp Q&A but i'll put it up here in hope of getting some answers.
I have a bunch of companies that has a status of 0 as default but sometimes get a higher status. Now i want to use the high status if exists but revert to 0 if not. i have tried a bunch of different approaches but i always get either only the ones with status 0 or the ones with the status i want, never giving me status if exists and 0 if not.
Gives me only the status i specify, not giving me the ones with status 0:
'Company' => array (
'conditions' => array (
'OR' => array(
'Company.status' => 0,
'Company.status' => $status,
)
)
)
Gives me only status of 0:
'Company' => array (
'conditions' => array (
'OR' => array(
'Company.status' => $status,
'Company.status' => 0
)
)
)
Status definition and retrieving data in code:
function getCountry($id = null, $status = null) {
// Bunch of code for retrieving country with $id and all it's companies etc, all with status 0.
$status_less_companies = $this->Country->find...
if ($status) {
$status_companies = $this->Country->find('first', array(
'conditions' => array(
'Country.id' => $id
),
'contain' => array(
'Product' => array (
'Company' => array (
'conditions' => array (
'OR' => array(
'Company.status' => $status,
'Company.status' => 0
)
)
)
)
)
)
}
// Mergin $status_less_companies and $status_companies and returning data to flex application.
}
I changed the name for the models for this question just to make more sense, people are generaly frighten away when i tell them i work with cakephp for my flex application. I guess the logic to this question doesn't make sense but trust me that it makes sense in my application.
Thanks!
Try
'Company' => array (
'conditions' => array (
'OR' => array(
array('Company.status' => 0),
array('Company.status' => $status),
)
)
)
In the cookbook it says to wrap the or conditions in arrays if they are pertaining to the same field
http://book.cakephp.org/2.0/en/models/retrieving-your-data.html#complex-find-conditions
I'm not sure to have understood what results you expect. If you want to retrieve all records having status = 0, plus let's say the one having status = 3, you could use an 'IN' instead of an 'OR'.
In Cake, you would write it like this:
$status = 3;
$conditions = array('Company.status' => array(0, $status));
You can also fetch record by using following method:
put values in an array
e.g. $arr=array(1,2);
$res = $this->Model->find('all', array(
'conditions' =>array('Model.filedname'=>$arr),
'model.id' => 'desc'
));
I hope you will find answer.
$this->loadModel('Color');
$colors = $this->Color->find('all', [
'conditions' => [
'Color.is_blocked' => 0,
'Color.is_deleted' => 0,
'OR' => [
[
'Color.isAdmin' => $user_data['id'],
],
[
'Color.isAdmin' => 0,
]
],
]
]);

Categories