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.
Related
Having this document structure in MongoDB :
{
"_id":<MongoDBID>,
"chatUser1ID": 2,
"chatUser2ID": 3
}
Now i want to get all chat partners from Mongo where the Chat Partner with the ID 2 is included in either "chatUser1" or "chatUser2". For that i want to use the $match and $group function.
$chatUserID = $_POST["chatUserID"]; // 2 in my example
$chatCursor = $chatCollection->aggregate([
[
'$match' =>
[
'$or' =>
[
["chatUser1ID" => $chatUserID],
["chatUser2ID" => $chatUserID]
]
]
]
,[
'$group' =>
[
'_id' => 0,
'chatUsers' => ['$addToSet' => '$chatUser1ID'],
'chatUsers' => ['$addToSet' => '$chatUser2ID'],
'chatUsers1' => ['$addToSet' => '$chatUser1ID'],
'chatUsers2' => ['$addToSet' => '$chatUser2ID'],
]
]
]);
'chatUsers1' => ['$addToSet' => '$chatUser1ID'],
This is putting all the ID's of the field chatUser1ID in the chatUsers1 set and
'chatUsers2' => ['$addToSet' => '$chatUser2ID']
is putting all all the ID's of the field chatUser2ID in the chatUsers2 set where the $chatUserID is either in the chatUser1ID or chatUser2ID field of the document.
After that i want want to get the unique ID's
$chatUserIDs = array();
foreach ($chatCursor as $counter => $document) {
$bson = MongoDB\BSON\fromPHP($document);
$value = MongoDB\BSON\toJSON($bson);
$value = json_decode($value, true);
$chatUserIDs = array_unique(array_merge($value['chatUsers1'], $value['chatUsers2']));
}
unset($chatUserIDs[array_search($chatUserID, $chatUserIDs)]);
array_unshift($chatUserIDs);
So basically it's working but i want the solution where i get a list of unique ID's right away from the database.
Originally i thought the lines
'chatUsers' => ['$addToSet' => '$chatUser1ID'],
'chatUsers' => ['$addToSet' => '$chatUser2ID'],
would add the ID's to the set chatUsers but unfortunately the set is overwritten in the second line. Is there a way to "append" the ID's to the set instead of overwrite them ? And maybe a way where i can exclude the $chatUserID because i want only the chatPartners.
Thanks in advance.
If you don't care about the order they appear in, you can build two arrays of user1 and user2, then concat them together in a later stage. This won't handle deduplicating though.
$chatUserID = $_POST["chatUserID"]; // 2 in my example
$chatCursor = $chatCollection->aggregate([
[
'$match' => [
'$or' =>[
["chatUser1ID" => $chatUserID],
["chatUser2ID" => $chatUserID]
]
]
], [
'$group' => [
'_id' => 0,
'chatUsers1' => ['$addToSet' => '$chatUser1ID'],
'chatUsers2' => ['$addToSet' => '$chatUser2ID'],
]
], [
'$addFields' => [
'chatUsers' => [
'$concatArrays' => [
'$chatUsers1',
'$chatUsers2'
]
]
]
],
]);
I have been using Elasticsearch 7.6 and PHP client API for all the operations.
I have created elasticsearch index settings and mappings as follows
$params = [
'index' => 'elasticindex',
'body' => [
'settings' => [
"number_of_shards" => 1,
"number_of_replicas" => 0,
"index.queries.cache.enabled" => false,
"index.soft_deletes.enabled" => false,
"index.requests.cache.enable" => false,
"index.refresh_interval" => -1
],
'mappings' => [
'_source' => [
"enabled" => false
],
'properties' => [
"text" => [
"type" => "text",
"index_options" => "docs"
]
]
]
]
];
I was able to index document using the following code
$params = array();
$params['index'] = 'elasticindex';
for($i = 1; $i <=2; $i++) {
$params['id'] = $i;
$params['body']['text'] = 'apple';
$responses = $client->index($params);
}
But when I use the following search query
$params = [
'index' => 'elasticindex',
'body' => [
'query' => [
'match' => [
"text" => "apple"
]
]
]
];
$results = $client->search($params);
I am getting empty results as follows
Array
(
[took] => 3
[timed_out] =>
[_shards] => Array
(
[total] => 1
[successful] => 1
[skipped] => 0
[failed] => 0
)
[hits] => Array
(
[total] => Array
(
[value] => 0
[relation] => eq
)
[max_score] =>
[hits] => Array
(
)
)
)
Without creating a static index template, if I try to index, elasticsearch dynamic mapping works well and I am getting the results.
The goal is that I want the elasticsearch to index only document id in its inverted index and not position or offset and I want to retrieve only matching document ids as results. Help is much appreciated. Thanks in advance!
Since the document is being returned by the get handler and not the query handler, your index is not being refreshed properly after indexing the document.
As you noted yourself, in your configuration you set:
"index.refresh_interval" => -1
.. which means that the index is not being refreshed automagically. There's seldom a need to change the refresh interval, except in very high throughput situations or where a particular behavior is wanted.
Try to index doc something like this.
$client = Elasticsearch\ClientBuilder::create()
->setHosts($hosts)
->build();
$params = [
'index' => 'elasticindex',
'type' => 'documents',
'id' => '1',
'body' => ['text' => 'apple']
];
$response = $client->index($params);
print_r($response);
Note: _id you can define dynamically if you want, else id will automatically set by elastic.
And try to get doc via a search query.
{
"query": {
"bool": {
"must": {
"term": {
"text": "apple"
}
}
}
}
}
If you want full-text search on this key, set this key property as
"properties": {
"name": {
"type": "text"
}
}
I have an array based MySql database.
This is the array.
[
0 => [
'id' => '1997'
'lokasi_terakhir' => 'YA4121'
]
1 => [
'id' => '1998'
'lokasi_terakhir' => 'PL2115'
]
2 => [
'id' => '1999'
'lokasi_terakhir' => 'PL4111'
]
]
How can I get the element lokasi_terakhir that grouped by the first character ? What the best way ?
This is the goal :
[
"Y" => 1,
"P" => 2
]
Please advise
Here are two refined methods. Which one you choose will come down to your personal preference (you won't find better methods).
In the first, I am iterating the array, declaring the first character of the lokasi_terakhir value as the key in the $result declaration. If the key doesn't yet exist in the output array then it must be declared / set to 1. After it has been instantiated, it can then be incremented -- I am using "pre-incrementation".
The second method first maps a new array using the first character of the lokasi_terakhir value from each subarray, then counts each occurrence of each letter.
(Demonstrations Link)
Method #1: (foreach)
foreach($array as $item){
if(!isset($result[$item['lokasi_terakhir'][0]])){
$result[$item['lokasi_terakhir'][0]]=1; // instantiate
}else{
++$result[$item['lokasi_terakhir'][0]]; // increment
}
}
var_export($result);
Method #2: (functional)
var_export(array_count_values(array_map(function($a){return $a['lokasi_terakhir'][0];},$array)));
// generate array of single-character elements, then count occurrences
Output: (from either)
array (
'Y' => 1,
'P' => 2,
)
You can group those items like this:
$array = [
0 => [
'id' => '1997',
'lokasi_terakhir' => 'YA4121'
],
1 => [
'id' => '1998',
'lokasi_terakhir' => 'PL2115'
],
2 => [
'id' => '1999',
'lokasi_terakhir' => 'PL4111'
]
];
$result = array();
foreach($array as $item) {
$char = substr($item['lokasi_terakhir'], 0, 1);
if(!isset($result[$char])) {
$result[$char] = array();
}
$result[$char][] = $item;
}
<?php
$array=[
0 => [
'id' => '1997',
'lokasi_terakhir' => 'YA4121'
],
1 => [
'id' => '1998',
'lokasi_terakhir' => 'PL2115'
],
2 => [
'id' => '1999',
'lokasi_terakhir' => 'PL4111'
]
];
foreach($array as $row){
$newArray[]=$row['lokasi_terakhir'][0];
}
print_r(array_flip(array_unique($newArray)));
this code gets the first letter of the fields lokasi_terakhir , get the unique values to avoid duplicates and just flips the array to get the outcome you want.
The output is this :
Array ( [Y] => 0 [P] => 1 )
I want to use aggregation to get this array only with those tickets, which have start field after 2015-06-16. Can someone help me with the pipeline?
{
"name" : "array",
"tickets" : [
{
"id" : 1,
"sort" : true,
"start" : ISODate("2015-06-15T22:00:00.000Z")
},
{
"id" : 2,
"sort" : true,
"start" : ISODate("2015-06-16T22:00:00.000Z")
},
{
"id" : 3,
"sort" : true,
"start" : ISODate("2015-06-17T22:00:00.000Z")
}
]
}
It's true that the "standard projection" operations available to MongoDB methods such as .find() will only return at most a "single matching element" from the array to that is queried by either the positional $ operator form in the "query" portion or the $elemMatch in the "projection" portion.
In order to do this sort of "ranged" operation, you need the aggregation framework which has greater "manipulation" and "filtering" capabilities on arrays:
collection.aggregate(
array(
# First match the "document" to reduce the pipeline
array(
'$match' => array(
array(
'tickets.start' => array(
'$gte' => new MongoDate(strtotime('2015-06-16 00:00:00'))
)
)
)
),
# Then unwind the array
array( '$unwind' => '$tickets' ),
# Match again on the "unwound" elements to filter
array(
'$match' => array(
array(
'tickets.start' => array(
'$gte' => new MongoDate(strtotime('2015-06-16 00:00:00'))
)
)
)
),
# Group back to original structure per document
array(
'$group' => array(
'_id' => '$_id',
'name' => array( '$first' => '$name' ),
'tickets' => array(
'$push' => '$tickets'
)
)
)
)
)
Or you can possibly use the $redact operator to simplify with MongoDB 2.6 or greater which basically uses the $cond operator syntax as it's input:
collection.aggregate(
array(
# First match the "document" to reduce the pipeline
array(
'$match' => array(
array(
'tickets.start' => array(
'$gte' => new MongoDate(strtotime('2015-06-16 00:00:00'))
)
)
)
),
# Redact entries from the array
array(
'$redact' => array(
'if' => array(
'$gte' => array(
array( '$ifNull' => array(
'$start',
new MongoDate(strtotime('2015-06-16 00:00:00'))
)),
new MongoDate(strtotime('2015-06-16 00:00:00:00'))
)
),
'then' => '$$DESCEND',
'else' => '$$PRUNE'
)
)
)
)
So both examples do the "same thing" in "filtering" the elements from the array that "do not" match the conditions specified and return "more than one" element, which is something basic projection cannot do.
You should use Aggregation to get output.
You should use following query:
db.collection.aggregate({
$match: {
name: "array"
}
}, {
$unwind: "$tickets"
}, {
$match: {
"tickets.start": {
$gt: ISODate("2015-06-16")
}
}
}, {
$group: {
"_id": "name",
"tickets": {
$push: "$tickets"
}
}
})
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.