Laravel - Eloquent Relationship not working in Mongo Using JsonArray - php

i am using mongoDB with Laravel. here is the Website document.
{
"_id" : ObjectId("5b68eeb2c2600fa0d42978fd"),
"site_name" : "Agent Inc",
"slug" : "agentinc",
"wp_env" : "production",
"wp_home" : "https://agentinc.co"
}
and here is the User document and i am using websites as Json Array in my User Document. like this.
{
"_id" : ObjectId("5c9e3ca99a8920189320ca62"),
"name" : "Usman Fakhar",
"website_ids" : [
"5be9cc00cd14658a0554a05d",
"5c0ebcdbb149d84483aa305d",
"5c10f676b149d84483acaa33"
],
"slug" : "usmanfc"
}
now in my User Model i am trying to use this relationship. but its not working.
public function websites(){
return $this->hasMany('App\Website', 'website_ids','_id');
}
this is returning an empty Collection when i try this.
$user->websites;

hello guys i was watching Documentation and there was an excellent relationship called "embedsMany" for this. so this code Worked.
return $this->embedsMany('App\Website', 'website_ids', '_id');

Related

How to update field in Mongo DB?

I have document like this:
{
"_id" : ObjectId("591ed2f0470e6ccc143c986e"),
"name" : "Planets",
"prototype_id" : null,
"parameters" : [
"591eefe3470e6cd70c3c9872",
"591eefc3470e6c500f3c9872",
"591eedbe470e6cd70c3c9871"
],
"available" : "1"
}
I tried to set [] for field parameters if value 591eefe3470e6cd70c3c9872 exists in this array.
I tried:
$new = array('$set' => array("parameters" => []));
$this->collection->update(array("parameters" => "591eedbe470e6cd70c3c9871"), $new);
It does not work...
MongoDB's update() and save() methods are used to update document into a collection. The update() method updates the values in the existing document while the save() method replaces the existing document with the document passed in save() method.
MongoDB Update() Method
The update() method updates the values in the existing document.
Syntax
The basic syntax of update() method is as follows −
db.COLLECTION_NAME.update(SELECTION_CRITERIA, UPDATED_DATA)
Consider the mycol collection has the following data
{ "_id" : ObjectId(5983548781331adf45ec5), "title":"MongoDB Overview"}
{ "_id" : ObjectId(5983548781331adf45ec6), "title":"NoSQL Overview"}
{ "_id" : ObjectId(5983548781331adf45ec7), "title":"My Overview"}
Following example will set the new title 'New MongoDB Tutorial' of the documents whose title is 'MongoDB Overview'.
db.mycol.update({'title':'MongoDB Overview'},{$set:{'title':'New MongoDB Tutorial'}})
db.mycol.find()
{ "_id" : ObjectId(5983548781331adf45ec5), "title":"New MongoDB Tutorial"}
{ "_id" : ObjectId(5983548781331adf45ec6), "title":"NoSQL Overview"}
{ "_id" : ObjectId(5983548781331adf45ec7), "title":"My Overview"}
By default, MongoDB will update only a single document. To update multiple documents, you need to set a parameter 'multi' to true.
db.mycol.update({'title':'MongoDB Overview'},
{$set:{'title':'New MongoDB Tutorial'}},{multi:true})

Pull mysql database into elasticsearch

I am using elasticsearch in my project and my requirement pulling a large MySQL data into Elasticsearch using Elasticsearch JDBC River plugin. My need is to sync mysql table to elasticsearch so i'm creating a mapping for jdbc river index.
curl -XPOST http://localhost:9200/city -d '
{
"mappings" : {
"city_type": {
"properties" : {
"domain" : {
"type" : "multi_field",
"fields" : {
"domain" : {
"type" : "string",
"index" : "analyzed"
},
"exact" : {
"type" : "string",
"index" : "not_analyzed"
}
}
},
"sent_date" : {
"type" : "date",
"format" : "dateOptionalTime"
}
}
}
}
}'
After creating the mapping in elasticsearch . i want to load the mysql table data into it. so i'm using the following command.
curl -XPUT 'localhost:9200/river/city/_meta?pretty' -d '{
"type" : "jdbc",
"jdbc" : {
"url" : "jdbc:mysql://localhost:3306/test",
"user" : "root",
"password" : "root",
"sql" : "select id as _id,id as domain from city;",
"strategy":"oneshot"
},
"index" :{
"index" : "city",
"type" : "city_type",
"bulk_size":500
}
}'
These queries are successfully run and after these query when i run the command to find the data in elasticsearch is empty.
http://localhost:9200/river/_search?pretty&q=*
Please check the response of the above query here. Why the data is not showing in the elasticsearch query please help.
River has been deprecated https://github.com/elastic/elasticsearch/issues/10345 by the way.
I would highly recommend jprante jdbc importer which is a java stand-alone allowing to do the operations you are needing. https://github.com/jprante/elasticsearch-jdbc. It is not exactly a river as you have defined one.
Concerning your question, could you please try http://localhost:9200/_search?pretty&q=* ? With your syntax, you are actually looking for data in index river. You should look on all index with the query I wrote or in city index : http://localhost:9200/city/city_type/_search?pretty&q=*
If I were in your shoes, I would use logstash to push the data from MySQL to Elastic. River is deprecated since a long time ago as #Artholl already mentioned.
See https://www.elastic.co/blog/logstash-jdbc-input-plugin

Intelligent searching with mongo

I am using phalcon with mongodb. I have the following document in collection:
{
"_id" : ObjectId("547c8b6f7d30dd522b522255"),
"title" : "Test vacancy",
"slug" : "test-vacancy",
"location" : "the-netherlands",
"contract" : "fixed",
"function" : "Test vacancy",
"short_description" : "gdfsgfds",
"description" : "fdsafsdgfsdgdfa",
"promo_text" : "gfdsgdfs",
"company_name" : "gfdsgfsd",
"hits" : 36,
"updated_at" : 1.42685e+09,
}
In controller I am fetching all results by searched phase/query. For example I put example word and output will be all posts with example word in description or title or short_desc etc. Everything is correct but I want sort these posts in specific order. I mean if query will be same as title, this post should be first. Now it is somewhere below.
Can you help me? Thank you in advance.

Limit returned fields with PHP MongoClient find() query

I am writing a PHP MongoClient Model which accesses mongodb that stores deploy logs with gitlab information, server hosts, and zend restart instructions. I have a mongo Collection called deployAppConfigs. Its document structure looks like this:
{
"_id" : ObjectId("54de193790ded22d1cd24c36"),
"app_name" : "ai2_api",
"name" : "AI2 Admin API",
"app_directory" : "path_to_app",
"app_owner" : "www-data:deployers",
"directories" : [],
"vcs" : {
"type" : "git",
"name" : "input/ai2-api"
},
"environments" : {
"development" : {
...
},
"qa" : {
...
},
"staging" : {
...
},
"production" : {
...
},
"actions" : {
"post_checkout" : [
"composer_install"
]
}
}
Because there are many documents in this collection, I would like to query the entire collection for only the "vcs" sub document and the "app_name". I am able to execute this command in Robomongo's mongo shell with the following find() query:
db.deployAppConfigs.find({}, {"vcs": 1, "app_name": 1})
This returns exactly what I want for each document in the collection:
{
"_id" : ObjectId("54de193790ded22d1cd24c36"),
"app_name" : "ai2_api",
"vcs" : {
"type" : "git",
"name" : "input/ai2-api"
}
}
I am having a problem writing a PHP MongoClient equivalent to that mongo shell command. I basically want to make a PHP MongoClient version of this mongo docs example on Limit Fields to Return from a Query
I have tried using an empty array to replace the "{}" in the mongo shell command like this, but it hasn't worked:
$query = array (
array(),
array("vcs"=> 1, "app_name"=> 1)
);
All the fields share the vcs.type = "git" so I tried wrote a query that selects all fields in every document based on that shared value. It looks like this:
$query = array (
"vcs.type" => "git"
);
But this returns the entire document, which is what I want to avoid.
The alternative could be to do a limit projection find() for the first document in the collection and then use the MongoCursor to iterate through the whole collection, but I'd rather not have to do the extra loop if possible.
Essentially, I am asking how to limit the return fields of a find() query to only one subdocument of each document in the entire collection.
looks like I was able to find the solution... I will solve the question and leave it up in case it ends up being useful to anyone else.
What I ended up having to do was alter my MongoClient custom class find() function, which calls the $collection->find() query, to include a $fields parameter.
Now, the MongoClient->find() query looks like this:
$collection->find(
array("vcs.type" => "git"),
array("vcs" => 1, "app_name" = 1)
)
Found the answer on the MongoClient::cursor::find() : here

Export from MySQL with relations to JSON (for CouchDB) with PHP

I’m working on my master thesis where one of my goals is to run tests and experiments against the CouchDB database and tune the performance.
To do that I need some test data. I’ve created a piece of php code to generate some simple relational data for a MySQL database. The tables are:
Customer
Product
Brand
Color
Checkout
I’ve made some relations between for example Product and Colorid and Brandid and in the Checkout table I’ve a relation to Customerid and Productid.
I want to export this entirely data structure and the data with its relations to a JSON format for CouchDB.
So I’ve a JSON string which should contain each customer with its attributes and its purchase with all the parameters for this product, and so on.
I’m thinking that it would look something like:
{
"customer": {
"customerid" : "1",
"firstname" : "somefirstname",
"lastname" : "somelastname",
"email" : "my#mail.com",
"country" : "USA",
"datecreated" : "11111111111111"
}
"purchase" : {
"purchaseid" : "1",
"product": {
"productname" : "mightymouse",
"productcolor": "blue",
"productbrand" : "Apple",
"productprice" : "200",
"checkoutdate" : "1111111111112"
}
"purchaseid" : "2",
"product": {
"productname" : "something nice",
"productcolor": "yellow",
"productbrand" : "Google",
"productprice" : "5000",
"checkoutdate" : "11111111113333"
}
}
}
It’s probably not the right data structure I’ve shown but it something like that.
Can this be done in PHP and if so, how do I create this kind of “CouchDB” ready JSON strings??
If I haven’t explained myself clearly, please let me know.
Thank you
Sincere
- Mestika
PHP has function json_encode, you can use it to convert any PHP object to its JSON representation (and json_decode to convert JSON string to object).
So:
Use PHP database functions to read data from database.
Create object of stdClass:
$data = new stdClass;
Fill this object with properties read from database like this:
$customer = new stdClass;
$customer->customerid = "1"
...
$data->customer = $customer;
Encode generated object with json_encode.

Categories