I have a document like this:
{
"_id" : ObjectId("5629aded0760cd72078b4567"),
"name" : "Name",
"url" : "URL.com",
"updated_at" : ISODate("2015-10-23T03:47:57.050Z"),
"created_at" : ISODate("2015-10-23T03:47:57.050Z")
}
And a function like this:
public function getByName($name) {
$findQuery = array("name" => $name);
$team = Team::find($findQuery);
print_r($team);
exit;
return "Here";
}
The problem is when I find by name field I alway get the empty array return. But when I try with $findQuery = array("_id" => "5629aded0760cd72078b4567"); it's work fine.
I don't know what did I do wrong here?
Related
I am using new mongodb driver for PHP and using query want to display all relevant documents. But instead it returns only one document or boolean(false) as value.
I want all the mongo documents to be returned which satisfies the condition. Tried using limit parameter option too but to no avail.
Below is my code :
<?php
ini_set("display_errors",1);
ini_set('error_reporting', E_ALL);
//$filter = [ 'job_id' => [ '$gte' => 1 ], ];
//$options = [ 'maxScan' => 400 ];
$mongo = new MongoDB\Driver\Manager("mongodb://localhost:27017");
$query = new MongoDB\Driver\Query([]);
$rows = $mongo->executeQuery('sag.jobs', $query, $readPreference); // $mongo contains the connection object to MongoDB
//var_dump($rows);
$abc=current($rows->toArray());
var_dump($rows);
//print_r($abc);
var_dump($abc);
?>
Used both with option and filters parameter and as a empty parameter :
Mongo table content:
> { "_id" : ObjectId("596608c7f4bb66cead9762d6"), "job_id" : 1 } { "_id"
> : ObjectId("596608caf4bb66cead9762d7"), "job_id" : 2 } { "_id" :
> ObjectId("596608cef4bb66cead9762d8"), "job_id" : 3 } { "_id" :
> ObjectId("596608d0f4bb66cead9762d9"), "job_id" : 4 } { "_id" :
> ObjectId("596608d2f4bb66cead9762da"), "job_id" : 5 }
and this is the only output I am getting :
object(stdClass)#6 (2) {
["_id"]=>
object(MongoDB\BSON\ObjectID)#5 (1) {
["oid"]=>
string(24) "596608c7f4bb66cead9762d6"
}
["job_id"]=>
float(1)
}
The following lines of code should give you the results as an array:
$client = new MongoDB\Client('mongodb://localhost:27017');
$arr = $client->sag->jobs->find($filter)->toArray();
For more information on the MongoDB\Collection::find method, see here. For more information on the MongoDB\Drive\Cursor object it returns, see here.
Hi I am new to mongodb..
My problem is to append array in mongodb data
My array
{
"_id" : ObjectId("5864f61111115810fc011111"),
"estimate" : {
"estimate_id" : 1122332,
"source_data" : {
"1" : {
"test":"test"
}
}
},
"updated_at" : ISODate("1970-01-15T10:47:01.399Z"),
"created_at" : ISODate("1970-01-15T10:41:56.623Z")
}
I want to add array in source_data like bellow
{
"_id" : ObjectId("5864f61111115810fc011111"),
"estimate" : {
"estimate_id" : 1122332,
"source_data" : {
"1" : {
"name":"nikhil"
},
"2" : {
"name":"nikhil"
}
}
},
"updated_at" : ISODate("1970-01-15T10:47:01.399Z"),
"created_at" : ISODate("1970-01-15T10:41:56.623Z")
}
I have tried below code but not working
$data = array("2"=>array("name":"nikhil"));
$sourcing = Sourcing::find('5864f61111115810fc011111');//return mongo data
$sourcing->put('estimate.source_data.2',$data );
To append one or more values to an array, the following which uses the push() method should work for you:
$data = array('name' => 'nikhil');
Sourcing::find('5864f61111115810fc011111')->push('estimate.source_data', $data);
I am attempting to update multiple array elements using a PHP version of the query described in how to update sequence number in mongodb safely
Which describes the query:
db.so.update(
{ _id: new ObjectId("4f55e7ba362e2f2a734c92f8")},
{ $set : { 'subs.1.order' : 3, 'subs.2.order' : 2 } }
);
I'm building a query to add an 'order' field to my document
{
"_id": {
"$oid": "5209acfd0de2316335000001"
},
"bookListId": "116ad5af-7cc6-4652-9bb3-aea852e584e8",
"favoriteBook": [
{
"title": "One Favorite Book",
},
{
"title": "Another Favorite Book",
},
{
"title": "A Third Favorite Book",
}
]
}
..and am doing it in PHP with
$criteria = array('bookListId' => $bookListId);
$favoriteBookOrder = array();
for($i=0;$i<sizeof($order);$i++) {
$key = 'favoriteBook.'.($i+1).'.order';
$val = $order[$i];
$favoriteBookOrder[] = array($key=>intval($val));
}
$setFavoriteBookOrder = array('$set' => $favoriteBookOrder);
$collection->update($criteria, $setFavoriteBookOrder);
but this doesn't produce any result because the query doesn't have the correct organization of arrays..
error_log(json_encode($setupdated));
outputs
{"$set":[{"favoriteBook.1.order":2},{"favoriteBook.2.order":1},{"favoriteBook.3.order":3}]}
which if you notice has too many quotes, brackets around the entire array, and curly braces around each item. I believe this is what is causing the error:
"Invalid modifier specified: $set"
What is the correct syntax for building the array in PHP? Thanks!
EDIT
this is the fix
$favoriteBookOrder[] = array($key=>intval($val));
should be
$favoriteBookOrder[$key] = intval($val);
also i removed the +1 from $i because Mongo indexes are 0 based
correct query now
{"$set":{"favoriteBook.0.order":1,"favoriteBook.1.order":2,"favoriteBook.2.order":3}}
To make you query work right you have to change one line:
$favoriteBookOrder[] = array($key=>intval($val));
to
$favoriteBookOrder[$key] = intval($val);
But I think you wont be happy with result, because it will something like this:
"favoriteBook" : {
"0" : { "order" : NumberLong(123) },
"1" : { "order" : NumberLong(321) },
"2" : { "order" : NumberLong(456) }
}
I suggest you rewrite code in this way:
for($i=0;$i<sizeof($order);$i++)
$favoriteBookOrder[$i]['order'] = $order[$i];
$setupdated = array('$set' => ['favoriteBookOrder' => $favoriteBookOrder]);
and you'll get:
"favoriteBookOrder" : [
{ "order" : NumberLong(123) },
{ "order" : NumberLong(321) },
{ "order" : NumberLong(456) }
]
P.S. you can play with $pushAll modificator instead of $set, it could be more suitable for you.
I have a mongodb collection of following format :
{
"_id" : ObjectId("5141916511e5b498fd2031c4"),
"itemid" : 1,
"recommendations" : [
{
"itemid" : 216,
"rating" : 0.875297364790784
},
{
"itemid" : 246,
"rating" : 0.8793363655122852
}
]
}
{
"_id" : ObjectId("5141916511e5b498fd2031c5"),
"itemid" : 2,
"recommendations" : [
{
"itemid" : 60,
"rating" : 0.9405825249353504
},
{
"itemid" : 76,
"rating" : 0.8822827294664317
}
]
}
I want to retrieve recommendations for a given itemid and then iterate over it to print all the recommended itemids and ratings.I am using php for this.
When I try to iterate over returned cursor,it throws "Fatal error: Call to a member function hasNext() on a non-object" error.
It seems the resultset returned by query is not of type cursor.
Below is the code I am using :
<?php
$mongodb = new Mongo("10.128.170.49:27017");
$database = $mongodb->ProductData;
$collection = $database->Recommendation1;
$cursor1 = $collection->findOne(array("itemid" => 1),array('recommendations'));
var_dump($cursor1);
echo "<hr/><p>iterating over a cursor</p>";
while ($cursor1->hasNext()): $document = $cursor1->getNext();
$itemid= $document['itemid'];
$probable_rating= $document['rating'];
echo ($itemid)."<br/>";
echo ($probable_rating)."<br/>";
echo "<hr/>";
endwhile;
?>
Please help me resolve this issue.
You have to change findOne() to find()
findOne() returns the first found result
find() returns a cursor
I have a script that is attempting to update a MongoDB collection with an xml response I've received from a server. I'm envoking simplexml_load_string() on the response. However, when updating the fields, it's adding an extra '0' key to the value I'm attempting to add. Here is the code:
$xml = simplexml_load_string($response);
if($xml->type == "reject") {
$status = $xml->type;
$message = $xml->message;
}
$update = array('$set' => array('status' => $status, 'response' => $message));
This is what I'm expecting:
{ "_id" : ObjectID("..."), "status" : "reject", "response" : "The message." }
However, here is the entry that is being saved in MongoDB:
{ "_id" : ObjectID("..."), "status" : { "0" : "reject" }, "response" : { "0" : "The message." } }
Any idea what is happening, or suggestions on how to fix it? Thanks!
$xml->type and $xml->message are probably objects, not strings. You might want to var_dump it to see what it actually is and then convert it to a string.