Mongodb strange updating - php

Trying to push some data to record using php
array('$push' => array(
"value" => 1,
"comment" => $data['comment'],
"status" => 1,
))
But in db I see following records like array :
And it's should be like a normal values :

Seems that you want to use $set instead of $push.
array('$set' => array(
"value" => 1,
"comment" => $data['comment'],
"status" => 1,
))
$push is for appending elements to embedded arrays. $set is for replacing field values.

Related

inserting value into PHP multi array

i am new in PHP coding, i wanna add some variable value in a multi array dynamically, below is my code...
$books = array (
"finality"=> array (
"title" => 1,
"author" => 2,
"thumbnail" => 3,
"file" => 4,
"comment" => 5,
),
"science"=> array (
"title" => 1,
"author" => 2,
"thumbnail" => 3,
"file" => 4,
"comment" => 5,
),
"morality"=> array (
"title" => 1,
"author" => 2,
"thumbnail" => 3,
"file" => 4,
"comment" => 5,
),
)
i want to add variables like. $title, $author, $pic2, $pic, $comment, in one array like $books['morality']. please help me.
If I undestand your question correctly, this is what you want.
$books['morality']['title'] = $title;
$books['morality']['author'] = $author;
$books['morality']['thumbnail'] = $pic2;
$books['morality']['file'] = $pic;
$books['morality']['comment'] = $comment;
If that's not what you are looking for try and be more precise in what you want to accomplish.
From what I understand, you would like to add a new item to the array.
Does the following look like what you need? If not, can you please try to clarify what it is that you would like?
$books[ $category ] = array(
"title" => $title,
"author" => $author,
"thumbnail" => $thumbnail,
"file" => $file,
"comment" => $comment
);

Get multidimensional array out of query

I am trying to get multidimensional array out of query and for some reasons it does not work.
I use query to retrieve data from mysql.
$sql = "SELECT Id, UserID, TimeAction, Command FROM users_checked WHERE UserId = 4 AND date(TimeAction) = '2016-12-05 '";
$q=$conn->query($sql);
$data = array();
while($r=$q->fetchAll((PDO::FETCH_ASSOC))){
$data[]=$r;
}
Array output
I should get array like printed below
$data = array(
array(
"Id" => "1",
"UserID" => "1",
"TimeAction" => "2016-11-29 08:00:00",
"Command" => "Prijava"
),
array(
"ID" => "1",
"USERID" => "1",
"TimeAction" => "2016-11-29 10:05:14",
"Command" => "Odjava"
),
array(
"Id" => "1",
"UserID" => "1",
"TimeAction" => "2016-11-29 12:22:14",
"Command" => "PoslovniIzlazak"
),
array(
"ID" => "1",
"USERID" => "1",
"TimeAction" => "2016-11-29 13:32:14",
"Command" => "Prijava"
),
array(
"ID" => "1",
"USERID" => "1",
"TimeAction" => "2016-11-29 16:00:00",
"Command" => "Odjava"
),
);
fetchAll - Returns an array containing all of the result set rows where as fetch - Fetches the next row from a result set.
So you have to use fetch instead of fetchAll if you want the data row wise.
Try this code.
while ($r = $q->fetch(PDO::FETCH_ASSOC))
{
$data[] = $r;
}
Reference:
fetch
fetchAll
You should probably use fetch_assoc() instead of fetch_all in your for loop, this way you can push the data you want into your array for each row of your mysql query result.
It would look like this :
$data = array();
while ($row = $r->fetch_assoc()) {
$row_array = array(
"Id" => row['Id'],
"UsedID" => row['UserID'],
"TimeAction" => row['TimeAction'],
"Command" => row['Command']
);
array_push($data, $row_array);
}
Please note I didn't test the code, I'm doing this by head.
Also, I'm guessing you didn't mean to write all Ids to "1" in your example.

mongodb: update nested document by an array?

I have a deeply nested PHP array which I saved as a document in Mongo and ended up with this structure:
{
"_id" : "...",
"categ1" : {
"aaa" : 112.6736,
"bbb" : 83.9137,
"ccc" : 80.3322,
.....
},
"categ2" : {
"xxx" : 1,
"yyy" : 22,
"zzz" : 7,
"subcateg" : {
"sub1" : 1,
"sub2" : 22
}
}
}
Now, I have another array with a similar structure and I would like to increase the values of the record, by the values of the modifier array:
$modifier=array(
'categ1' => array(
'aaa' => 3,
'bbb' => -1,
'mmm' => 11
),
'categ2' => array(
'yyy' => -2,
'subcateg' => array(
'sub1' => -1
)
)
);
How can I increase the values inside the document by the values of the $modifier all at once, in a single query, and without loading the entire document ?
I've looked around the web but couldn't find any info on this.
Also, i'm pretty newbie at Mongo. Thanks
You can get your $modifier array to look like this:
$modifier = array(
'categ1.aaa' => 3,
'categ1.bbb' => -1,
'categ1.mmm' => 11,
'categ2.yyy' => -2,
'categ2.subcateg.sub1' => -1
)
Link for how to get that.
Then you should be able to simply use:
$col->update(
array("_id" => "..."),
array('$inc' => $modifier),
array("upsert" => true)
);

MongoDB : Insert and Update in an array

I have "_id" and "ProductLot". How can I Update Qty "0" to "1 " in the Lot array if ProductLot if present or append a new Lot element if it is not present?
"_id" : ObjectId("5462e44c599e5c6c1300000a"),
"LocationName" : "Putaway",
"Owner" : "",
"Status" : "1",
"Scrap" : "0",
"Lot" : [{
"Qty" :"6",
"ProductLot" : ObjectId("5462dbd9599e5c200e000000"),
"Product" : ObjectId("543ca7be4cf59d400c000004"),
"Movement" :[ {"OriginId" : "266",Qty:2,Type:"DN"},
{"OriginId" : "267" , Qty:1 , Type:"DN"},
{"OriginId" : "2" , Qty:3 , Type:"IM"},
]
},
{
"Qty" :"0",
"ProductLot" : ObjectId("5462dbd9599e5c200e000003"),
"Product" : ObjectId("543ca7be4cf59d400c000004"),
"Movement" :[ {"OriginId" : "266",Qty:2,Type:"DN"},
{"OriginId" : "267" , Qty:1 , Type:"DN"},
{"OriginId" : "2" , Qty:-3 , Type:"IM"},
]
}]
}
EG: I have "ProductLot" : ObjectId("5462dbd9599e5c200e000000") present in array so it should update qty 0 to 1; however, "ProductLot" : ObjectId("5462dbd9599e5c200e00000a") is not available in array so that should append a new element to the array.
PHP code, which is not updating creating appending array at every time:
$inventoryId = new \MongoId($_POST["inventoryid"]);
$productLotId = new \MongoId($invlotid);
$originId = $_POST['id'];
//$lotcontent = [ /* whatever this looks like */ ];
$lotcontent = array(
'Qty' => $invqty,
'ProductLot' => new \MongoId($invlotid),
'Product'=>$invproduct,
'Movement'=> array(
array(
'OriginId' => $_POST['id'],
'Qty' => $invqty,
'Type'=> 'DN',
), )
);
$invcolname = 'Inventory';
$result = $mongo->$dbname->$invcolname->update(
// Match an inventory without the specific ProductLot/OriginId element
array(
'_id' => $inventoryId,
'Lot' => array(
'$not' => array(
'$elemMatch' => array(
'ProductLot' => $productLotId,
//'OriginId' => $originId,
),
),
),
),
// Append a new element to the Lot array field
array('$push' => array( 'Lot' => $lotcontent ))
);
$movementcontent = array(
'OriginId' => $_POST['id'],
'Qty' => $invqty,
'Type'=> 'DN',
);
$result = $mongo->$dbname->$invcolname->update(
// Match an inventory without the specific ProductLot/OriginId element
array(
'_id' => $inventoryId,
'Lot' => array(
//'$not' => array(
'$elemMatch' => array(
'ProductLot' => $productLotId,
'Movement'=>array(
'$not' => array(
'$elemMatch' => array(
'OriginId' => $originId,
)
)
)
),
// ),
),
),
// Append a new element to the Lot.Movement array field
array('$push' => array( 'Lot.$.Movement' => $movementcontent ))
);
$result = $mongo->$dbname->$invcolname->update(
// Match an inventory with a specific ProductLot/OriginId element
array(
'_id' => $inventoryId,
'Lot' => array(
'$elemMatch' => array(
'ProductLot' => $productLotId,
//'OriginId' => $originId,
'Movement'=>array(
'$elemMatch' => array(
'OriginId' => $originId,
)
)
),
),
),
// Update the "Qty" field of the first array element matched (if any)
//array( '$set' => array( 'Lot.$.Qty' => 'Updated' )),
array( '$set' => array( 'Lot.$.Movement.$.Qty' => $invqty )),
array('upsert' => true));
Please anyone help me to resolve this?
Using $addToSet is problematic in this case, because the following lot elements would be considered different:
{
"Qty" :0,
"ProductLot" : ObjectId("5462dbd9599e5c200e000003"),
"Product" : ObjectId("543ca7be4cf59d400c000004"),
"OriginId" : "266"
}
{
"Qty" :5,
"ProductLot" : ObjectId("5462dbd9599e5c200e000003"),
"Product" : ObjectId("543ca7be4cf59d400c000004"),
"OriginId" : "266"
}
The first element is likely what you would be adding (either with quantity 0 or 1), and the second element would be the same logical lot element, just with an incremented quantity. If the latter element already existed in the array, I imagine you'd like for your application to increment the quantity from 5 to 6 instead of adding the first element, which is essentially a duplicate.
We definitely need two updates here, but I would propose the following:
// Let's assume the following identifiers...
$inventoryId = new MongoId($_POST['inventoryid']);
$productLotId = new MongoId($invlotid);
$originId = new MongoId($_POST['id']);
$lotcontent = [ /* whatever this looks like */ ];
$result = $collection->update(
// Match an inventory without the specific ProductLot/OriginId element
[
'_id' => $inventoryId,
'Lot' => [
'$not' => [
'$elemMatch' => [
'ProductLot' => $productLotId,
'OriginId' => $originId,
],
],
],
],
// Append a new element to the Lot array field
[ '$push' => [ 'Lot' => $lotcontent ] ]
);
MongoCollection::update() will return a result document with an n field indicating the number of affected documents. Since we aren't using the multiple option and are also matching at most one document by _id, we can expect n to be either 0 or 1. If n was 0, we either couldn't find an inventory document with that _id or we found one but it already had a Lot element with the product and origin identifiers (i.e. our $elemMatch criteria matched something, invalidating our negation). If n was 1, that means we found the inventory document, it did not contain a matching Lot element, and we appended it (i.e. our job is done).
Assuming n was 0, we should issue another update and attempt to increment the quantity:
$result = $collection->update(
// Match an inventory with a specific ProductLot/OriginId element
[
'_id' => $inventoryId,
'Lot' => [
'$elemMatch' => [
'ProductLot' => $productLotId,
'OriginId' => $originId,
],
],
],
// Update the "Qty" field of the first array element matched (if any)
[ '$inc' => [ 'Lot.$.Qty' => 1 ] ]
);
Here, I'm using the $ positional update operator to access a specific array element that was matched in the criteria. This allows us to craft an $inc without worrying about the index of the matched element.
Again, we can check $result['n'] here. If it's still 0, then we can assume that no document matches our _id (a completely separate error). But if n is 1 at this point, we successfully incremented the quantity and our job is done.

Getting correct JSON format

So I am trying to make a JSON object that should hold some information about some questions for me. This is a pseudo-code of how I want it to be presented:
{
"page" : 1,
"info" :
{
"id" : 1,
"type" : 3,
"description": "How to do JSON?",
"alternatives" :
{
"id" : 1,
"description" : "Dunno"
}
{
"id" : 2,
"description" : "Let me show you"
}
{
"id" : 3,
"description" : "I refuse to show you"
}
}
"id" : 2,
"type" : 1,
"description": "Do you get it?",
"alternatives" :
{
"id" : 1,
"description" : "Yes"
}
{
"id" : 2,
"description" : "No"
}
}
}
So the code underneath is from Nightmare (one of the answers), and it does exactly what I want to do with the page and the questions, but I can't seem to figure out how to connect alternatives to each question. You can see a snippet at the bottom where I have tried but it's not correctly spelled and I've been hammering at this for a while now.
$before_json_encode[$row['page']][] = array(
'id' => $row['id'],
'type' => $row['type'],
'description' => $row['description'],
'alternatives' => $alternativesarray//im not sure about here,dont know the structure of the alternative array
);
Another illustration on how I want the hierarchy of the JSON data to appear. I need to be able to pick for instance: All alternatives to all questions on a specific page. So if I want to generate page 3 in my poll I can first find the questions within the page 3 sub-array, and then again from each question gain access to all of it's connected alternatives in that questions's own sub-array. Sorry for the poor explanation of my issue, it's just a bit complicated :/
Page
Question
Alternative
Alternative
Alternative
Question
Alternative
Alternative
Alternative
Question
Alternative
Alternative
Page
Question
Alternative
Alternative
Question
Alternative
Alternative
Update: 3rd layer:
$rows_test2[$r['page']]
['id' => $r['id'],
'type' => $r['type'],
'description' => $r['description']]
[] =
array (
'altid' => $t['altid'],
'altdesc' => $t['altdesc']);
$rows[] = array(
"page" => 1,
"info" => array(
"id" => 1,
"type" => 3,
"description" => 'desc',
)
);
echo json_encode($rows); // [{"page":1,"info":{"id":1,"type":3,"description":"desc"}}]
Update:
$alternativesarray[]=array('id'=>'1', 'description'=>'yes');
$alternativesarray[]=array('id'=>'2', 'description'=>'no');
$rows[] = array(
"page" => 1,
"info" => array(
"id" => 2,
"type" => 3,
"description" => 'desc',
"alternatives" => $alternativesarray
)
);
print json_encode($rows); // [{"page":1,"info":{"id":2,"type":3,"description":"desc","alternatives":[{"id":"1","description":"yes"},{"id":"2","description":"no"}]}}]
maybe like this?
$before_json_encode[$row['page']][] = array(
'id' => $row['id'],
'type' => $row['type'],
'description' => $row['description'],
'alternatives' => $alternativesarray//im not sure about here,dont know the structure of the alternative array
);

Categories