How would you remove an array item from a mongodb field . For example , how do i remove guitar from the list of interest . Any PHP functions or approaches would help.
{
"_id" : ObjectId("4d1cb5de451600000000497a"),
"name" : "dannie",
"interests" : [
"guitar",
"programming",
"gadgets",
"reading"
]
}
unset($array['interests']['guitar']) if this is array in PHP
you can use unset() function for this task.
Thanks.
Actually it should be
$key = array_search('guitar', $array['interests']);
unset($array['interests'][$key]);
as guitar is not a key for interests.
Related
I have a line of code similar to the following:
Sport::pluck('id', 'name)
I am dealing with frontend JavaScript that expects a list in this format:
var list = [
{ text: 'Football', value: 1 },
{ text: 'Basketball', value: 2 },
{ text: 'Volleyball', value: 3 }
...
]
I am trying to figure out how I can somehow transform the id and name values that I pluck from my model to a format similar to the Javascript list.
If that's unclear, I am looking to end up with an associative array that contains two keys: text and value, where text represents the name field on my model, and where value represents the id of the model - I hope this makes sense.
How would I approach this?
I initially tried something like this (without checking the documentation)
Sport::pluck(["id" => "value", "name" => "text]);
But that isn't how you do it, which is quite clear now. I've also tried some map-related snippet, which I cannot seem to Ctrl-z to.
Any suggestions?
Another method is to use map->only():
Sport::all()->map->only('id', 'name');
The purpose of pluck is not what you intend to do,
Please have a look at below examples,
Sport::selectRaw("id as value, name as text")->pluck("text","value");
// ['1' => 'Football', '2'=>'BasketBall','3'=>'Volleyball',...]
Syntax
$plucked = $collection->pluck('name', 'product_id');
// ['prod-100' => 'Desk', 'prod-200' => 'Chair']
Please see the documentation.
Your output is possible using simple code.
Sport::selectRaw('id as value, name as text')->get();
You could use map.(https://laravel.com/docs/5.8/collections#method-map)
$mapped = Sport::all()->map(function($item, $index) {
return [
"id" => $item["id"],
"name" => $item["text"]
];
});
This is the easiest way. Actually Laravel offers a better way for it. You can use api resources to transform your data from eloquent for the frontend:
https://laravel.com/docs/5.8/eloquent-resources
Try with toArray function:
Sport::pluck('id', 'name)->toArray();
Then you can return your result with json_encode php function;
I am setting up a Jquery autosuggest using ajax and I have a simple query to the database which returns 5 suggestions. The fields are company and id, so I get
$result['id']
$result['company']
for each row of the returned database suggestiions
This works fine and currently I loop over the results
foreach ($result as $item) {
$suggest[] = $item['company'];
}
echo json_encode($suggest);
I want though to add these so the company is a label and id is a value, something like
"value": "A Company", "data": "20"
This I can then encode and use in my autosuggest.
Thanks in advance!
You have to save an array to main array like this
foreach ($result as $item) {
$suggest[] = [
'value' => $item['company'],
'data' => $item['id'],
]
}
echo json_encode($suggest);
And it should return something like this
[
{
'value': 'Some value',
'data' : item id
}
]
i will recommend you create an array, next create 2 more arrays as values for the value and data keys.
like this.
$arr=array();
$arr['value']=array();
$arr['data']=array();
while($suggest=mysql_fetch_assoc($result)){
array_push($arr['value'],$suggest['id']);
array_push($arr['data'],$suggest['company']);
}
echo "<pre>";
print_r($arr);
note that with this solution, if you delete an entry in either value or data
be ready to delete the corresponding entry in the other array.
others may be able to improve this or even offer a better approach.
I have an array of 3 companies, which need to be inserted into the db but with 2 additional parameters added to them.
$companyList = [{"name": "apple", "founder": "steve"},
{"name": "google", "founder": "larry"},
{"name": "facebook", "founder": "mark"},
];
Need to append these 2 parameters for each company (issue is in this step):
$companyListFinal = [];
foreach ($companyList as $company) {
$companyListFinal[] = array_add($company,['keyAppend1' => 'key 1 appended',
'keyAppend2' => 'key 2 appended'];
}
The final step is to insert the company list with the appended values into the DB:
DB::table('companies')->insert($companyListFinal);
I can't seem to be able to append the 2 new parameters to create the final array to insert:$companyListFinal
What's the correct way to add the parameters to each company so they are all inserted at bulk?
You need to use array_merge instead of array_add
Try using array_push() instead on array_add(). That should do the job.
I would like to update a couple of elements in they match given values:
Example : I have a collection with this structure:
{
"_id" : ObjectId("52936a0270c68c04063f0300"),
"channel" : "1",
"content" : "145548",
"keywordsValues" : [
[ObjectId("52816d3370c68c2c1c4b0500"), ObjectId("52816d3370c68c2c1c9f0500")],
[ObjectId("52816d3370c68c2c1c510500"), ObjectId("52816d3370c68c2c1c890500")],
[ObjectId("52816d3370c68c2c1c550500"), ObjectId("52816d3370c68c2c1c850500")],
[ObjectId("52816d3370c68c2c1c6b0500"), ObjectId("52816d3370c68c2c1c990500")]
]
}
And I need to update "keywordsValues" field (just one of the couple in the array [])
Something for example update the 2nd element in keywordsValues:
If we found [firstId,secondId] in keywordsValues field then update the second secondId
$database->Measurements->update(
array('keywordsValues'=>
array(new MongoId(52816d3370c68c2c1c4b0500),new MongoId(52816d3370c68c2c1c9f0500)',$atomic'=>'true')),
array('$set'=>array('keywordsValue.$'=>new MongoId($idNewValue))));
But this doesn't work...
try
array('$set'=>array('keywordsValue'=>new MongoId($idNewValue))));
instead of
array('$set'=>array('keywordsValue.$'=>new MongoId($idNewValue))));
i hope it help to you!
I am building a simple messaging system, and i have a collection in mongodb with documents like this:
{ "_id" : ObjectId("50ad003f9811e5bc5c000000"), "between" : [ "user1,user2,user3" ] }
I want to perform this query:
db.conversations.find({'between': ["user1,user2,user3"]});
to get this exact document back. This query works in mongo shell.
in php-mongo, i tried this:
$collection->find(array("between"=>array("user1", "user2", "user3")));
but it does not work.
What am i doing wrong ?
Wouldn't you want to do an In query here?
db.collection.find( { "between" : { $in : ["user1", "user2", "user3"] } } );
See In query here:
Mongo Advanced $in query
making your PHP query look like:
$collection->find(array("between"=>array("$in"=>array("user1", "user2", "user3"))));
//untested, should be something similar to this.
or if you're trying to find it exactly wouldn't you just be able to do:
$collection->find(array("between"=>array("user1,user2,user3")));
First of all when you are saving your data you have to use array not a string
{ "between" : [ "user1,user2,user3" ] }
this stores in "between" an array of one element "user1,user2,user3"
Basically when you do your query in shell everything is ok, because you are asking for a array with one element. But in php you are asking for an array of three elements.
So, when you save your data, most probably that is what you need :
{ "between" : [ "user1","user2","user3" ] }
and this will give you an array of three users.
Then read the documentation http://www.mongodb.org/display/DOCS/Advanced+Queries to and adjust your query depends on what you need: either the exact array or only some elements in the array
Have you tried:
$collection->find(array("between"=>"user1,user2,user3"));
or
$collection->find(array( "$elemMatch" => array( "between"=>"user1,user2,user3" ));
The $in operator is analogous to the SQL IN modifier, allowing you to specify an array of possible matches.
Consider the following example which uses the $or operator.
$collection->find([
'select' => ['$in' => ['option 1', 'option 2', 'option 3']]
]);
References