MongoDB & PHP get only product that matches barcode - php

I have this JSON and you can see under products i have barcodes for each product what i want to do is only get the information that matches the product barcode
{
"company": "village",
"logo": "http:\/\/www.incard.com.au\/newsite\/template\/images\/movieticket\/4cinemas\/villagetop.png",
"products": [
{
"barcode": "236690091",
"name": "Weekday",
"logo-URL": "http: \/\/www.incard.com.au\/newsite\/template\/images\/movieticket\/4cinemas\/ticketpic1.png",
"price": "12.50",
"discount": "1.50"
},
{
"barcode": "236690092",
"name": "Weekend",
"logo-URL": "http: \/\/www.incard.com.au\/newsite\/template\/images\/movieticket\/4cinemas\/ticketpic1.png",
"price": "13.50",
"discount": "1.60"
},
{
"barcode": "236690093",
"name": "Gold Class",
"logo-URL": "http: \/\/www.incard.com.au\/newsite\/template\/images\/movieticket\/4cinemas\/ticketpic1.png",
"price": "13.50",
"discount": "1.60"
}
],
"store_name": "movies"
}
for example If i hit 236690091 I only what the database (MongoDB) to return
"barcode": "236690091",
"name": "Weekday",
"logo-URL": "http: \/\/www.incard.com.au\/newsite\/template\/images\/movieticket\/4cinemas\/ticketpic1.png",
"price": "12.50",
"discount": "1.50"
not every product.
This is what I have tried
public function getbarcode($barcode)
{
// select a collection (analogous to a relational database's table)
$collection = $this->db->movies->products;
// find everything in the collection
$cursor = $collection->find(array("barcode" =>"{$barcode}"));
$test = array();
// iterate through the results
while( $cursor->hasNext() ) {
$test[] = ($cursor->getNext());
}
//Print Results
print json_encode($test);
}

You can't do this. MongoDB will always return the full document and will not allow you to return only a nested part that you want to search against. I would suggest to split out the products into its own collection, and then add the company info to each product. This will also circumvent the 16MB document limit in case you have lots of products for each company.
Without changing your schema, the following code should work:
public function getbarcode($barcode)
{
$products = array();
$collection = $this->db->movies->products;
foreach( $collection->find( array( 'products.barcode' => $barcode ) ) as $item )
{
foreach( $item->products as $product )
{
if ( $product['barcode'] == $barcode )
{
$products[] = $item;
}
}
}
return $products;
}

You can't do this the way you want. MongoDB will return only whole documents or some fields from the documents (if you specify them in query). You can't return only values that are matched by your query.
You can create a separate collection that will only hold the products objects (with a reference to a collection that holds the company data) where you can directly query for the product data you want.
If you can't / won't create another collection you can find all documents that have the product with specified barcode and filter them out using PHP.
For this second approach your query should be:
$collection->find(array("products.barcode" =>"{$barcode}"),
array('products' => 1));
With this query you're reaching into objects and returning only documents that have the barcode you are looking for.
Also, in this query you will only return the products property from your document and not the whole document. The products property will contain all the child objects, not just the one you are trying to find.
In your while loop you should check the values and filter them out properly.

Related

How do I add a document to existing filled collection?

I am building an eShop for educational purposes and I need to handle the orders from a user. A user has a basket which is getting filled with products. If he decides buy another product I have insert a document into the existing collection of the card
Current MongoDB collection:
{
"_id": {
"$oid": "61f3d79c921000006000547d"
},
"username": "mike",
"products": {[
"number": "3",
"name": "Honduras",
"price": 7,
"stock": 10,
]},
"status": "UNPAID"
}
By adding another product, needs to be inserted in the existing collection in the field of products.
Expected to look like:
{
"_id": {
"$oid": "61f3d79c921000006000547d"
},
"username": "mike",
"products": {[
"number": "3",
"name": "Honduras",
"price": 7,
"stock": 10,
], [
"number": "4",
"name": "India",
"price": 10,
"stock": 11,
]},
"status": "UNPAID"
}
I am using PHP for the back end operations. The script that I wrote it is simple. I am searching if orders with user's username exist. If they exist then I lock the current order and make the operations needed.
I think that I am missing something in syntax of the update for the purpose described above:
PHP script:
if (isset($_POST['add'])){
// Ordered by name from URL
$username = $_GET['username'];
// Product info
$name = $_POST['add'];
// Finds the product selected from products
$product = $collection -> findOne(array("name" => "$name"));
// Serialize product to be added.
$json = MongoDB\BSON\toJSON(MongoDB\BSON\fromPHP($product));
// Searching for order from certain user
$collection = $db -> orders;
$exists = $collection -> findOne(array("username" => "$username"));
if (!is_null($exists)){
// The problem is here (maybe?)
$exists->updateOne(
array("products" => {}),array('$set'=>$json);
);
}
Any help and suggestions would be really appreciated!
Well, you need to use something like below
db.collection.update(
{find Condition},
{$push: {products : {key: value, key2: value 2}}
)
Here the catch is push. It adds an element to array. Here the element is an object.

Retrieve array object in a table from another table data id using a where clue in laravel

Question: I have two tables how to fetch a customer's data using order's table user_id
"order": [
{
"id": 1,
"user_id": 4
},
{
"id": 2,
"user_id": 5
}
],
"customers": [
{
"id": 5,
"name": "Mohamed Raazi",
"phone": "777",
}
],
Following code will return only the last object of an array, i need to display all the objects from user table using a where condition in customers table
for ($x=0; $x<count($orders); $x++){
$customer = User::where('id',$orders[$x]->user_id)->get();
}
I would use the ::whereIn-method where you can provide an array of IDs to and get all the users with the provided IDs.
First you would have to reformat the $orders array that you have so that it contains only user IDs. I am guessing that you are using Eloquent to fetch the orders, then you can use the pluck-function in your Eloquent-statement:
$userIds = Order::where('statement', true)->pluck('user_id')->toArray();
Please note that the where-statement is not real, I just want to illustrate how you can call the pluck-method.
Another alternative is that you use the map function on the $orders-collection and return only user IDs:
$userIds = $orders->map(function ($order) {
return $order->user_id;
});
Once you have your user IDs in an array/collection you can use it in the whereIn-statement:
$users = Users::whereIn('id', $userIds)->get();
Then this would give you all the users that that are connected to the orders you have in your order-collection.

MongoDB Getting all documents that have the same foreign key

I have the following sets of data : supposing this is a 'category' collection, each category has a parent 'category' and belongs to a 'section' which is another collection :
{
"_id": ObjectId("5379e61b086d83de218b4568"),
"name": {
"en": "Inactive accounts"
},
"parent": ObjectId("5379e61b086d83de218b4568"),
"section": "ObjectId("5379d4f9086d835328a22fc8")
}
{
"_id": ObjectId("5379e61b086d83de218b4568"),
"name": {
"en": "second category"
},
"parent": 0,
"section": "ObjectId("5379d4f9086d835328a22fc8")
}
etc......
I'm trying to get all categories in the same section : here is my php code :
$categories = $db->categories->find(array('section' => new MongoId($section)));
In this case it returns {} an empty result, while if used findOne it returns one document.
$categories = $db->categories->findOne(array('section' => new MongoId($section)));
I'm not sure if I missed something, I may change foreign keys to strings instead of ObjectId('')s.
I solved it , I was processing the response incorrectly. the code above was working but 'find' function returns 'Cursor' while findOne return array.

searching for a way to filter results by a field defined in another linked table using Doctrine and MongoDB

I need to find a way to filter results from a MongoDB database, based on fields found in the current table, and a field found in another table which is linked to the current table. Tables format:
{
"_id": ObjectId("51af256a0da4dd7804000007"),
"enddate": ISODate("2013-06-14T21:00:00.0Z"),
"main": false,
"name": "name 1",
"photo": "image-1.jpg",
"site": {
"$ref": "Sites",
"$id": ObjectId("51ac538c5f06751414bd9f98"),
"$db": "local"
},
"startdate": ISODate("2013-04-30T21:00:00.0Z")
}
{
"_id": ObjectId("51d3d5b9caa8213b12e92c5e"),
"sitefeatured": false,
"sitename": "a",
"sitephoto": "aa.jpg",
"siteurl": "aaaa.com/"
}
what i`m trying to do in ->where clause is to search in the string formed by this.name and this.site.sitename:
my problem is that i don't know / didn't find how to reference to property sitename of the site object
$entries = $dm
->getRepository($sTable)
->createQueryBuilder('o')
->where('function() { return ( (this.name + this.site.sitename).toLowerCase().indexOf("'.$_GET['sSearch'].'".toLowerCase()) !== -1 ) ? true : false }')
->sort($aColumns[$_GET['iSortCol_0']], $_GET['sSortDir_0'])
->limit($_GET['iDisplayLength'])
->skip($_GET['iDisplayStart'])
->getQuery()
->execute();
Is there anything like SQL join that i didn't came across, or what's the solution?

MongoDB Group by Key PHP

Ok, so I have a collection in my MongoDB
here is a sample my key here is
company
{
"_id": ObjectId("4fdfe7b536314b4147000000"),
"company": "hoyts",
"barcode": "236602253",
"name": "Gold Class",
"logoURL": "http: \/\/www.incard.com.au\/newsite\/template\/images\/movieticket\/4cinemas\/ticketpic1.png",
"store_name": "movies"
}
Now the issue here is I have 4 rows/collects with hoyts, I need away to group them.
my current code
public function getstore($storename)
{
// select a collection (analogous to a relational database's table)
$collection = $this->db->products;
// find everything in the collection
$cursor = $collection->find(array("store_name"=>$storename));
$test = array();
// iterate through the results
while( $cursor->hasNext() ) {
$test[] = ($cursor->getNext());
}
//Print Results
print json_encode($test);
}
I tried using
group($key)->find
however that did not work.
Could someone give me a hand thanks
look at this example: http://php.net/manual/en/mongocollection.group.php

Categories