having this weird issue while inserting to MongoDB using PHP. My insertion code is as follows :
$tyre = array("m" => '5', "i" => 'test.png');
$tyreCollection->insert(array($tyre),array('safe'=>true));
After insertion, I see the following in my DB :
{'_id' : ObjectId("856876876786867"),"0":{"m":'5','i':'test.png'}}
Why does my new array have a key of 0 ? I am expecting :
{'_id' : ObjectId("856876876786867"),"m":'5','i':'test.png'}
What am I doing wrong ?
Insert only $tyre instead of array($tyre)
$tyreCollection->insert($tyre,array('safe'=>true));
Also always remember to dump variables with var_dump or print_r
Related
Following is the query i had written to get the count based on event name.
$data= DB::collection(Events::$collection)->raw(function($collection) {
return $collection->aggregate([
['$match' => ['appid' => 1]],
['$group' => ['_id' =>['Event' =>'$Event'], 'count' =>['$sum'=>1]]]
]);
});
When i print the above query using laravel eloquent query logs its displays the output as follows :
Array (
[query] => events.aggregate([{"$match":{"appid":1}},{"$group":{"_id":{"Event":"$Event"},"count":{"$sum":1}}}])
[bindings] => Array ( ) [time] => 9.93
)
DB Query As Follows:
db.events.aggregate([{"$match":{"appid":1}},{"$group":{"_id":{"Event":"$Event"},"count":{"$sum":1}}}])
The same thing if i run in NoSQLBooster for MongoDB then its retuning the result properly.
But the laravel mongodb query from the above is returning empty result.
I am not getting what is the problem. Needs help.
I am using following version of laravel and mongodb.
Laravel Version : 5.4
MongoDB Version : 3.6
Thanks in Advance.
I have written following code for aggregation of two tables in php application
$lookupTwo = array(
'$lookup'=> array(
"from" => "studentTbl",
"localField" => "studentDetailId",
"foreignField" => "studentId",
"as" => "recieverDetails"
)
);
Now I am facing an issue, the studentDetailId field is stored as a string and studentId is stored as an integer.
The above query will return empty result.
Is there any possibility for performing aggregation in such case?
I have the following Mongodb Documents :
Users : {'_id' : '12345', 'fullname' : 'ABC'}
and
Files :
{'_id' : 'File001', 'path' : 'pathA', 'Users_id' : '12345'}
{'_id' : 'File002', 'path' : 'pathB', 'Users_id' : '12345'}
How do i query or find all 'Files' documents in a way that the 'Users_id' which is referencing to the 'Users' document has the full 'Users' Document?
Expected Output :
{'_id' : 'File001', 'path' : 'pathA', 'Users_id' : '12345', 'user' : {'_id' : '12345', 'fullname' : 'ABC'}}
{'_id' : 'File002', 'path' : 'pathB', 'Users_id' : '12345', 'user' : {'_id' : '12345', 'fullname' : 'ABC'}}
In this way, i could access the file owner's fullname as such : file.user.fullname
I Appreciate any help from you guys. Thank you.
--- EDIT
I am using node-mongodb-native to access the db.
Below is my code to retrieve it:
var files = db.collection ('Files');
files.find ({}, {}).toArray (function ( err, filesDoc){
for ( var index in filesDoc) {
var fileDoc = filesDoc [ index ];
var users = db.collection ('Users');
users.findOne ({'_id' : fileDoc.Users_id}, {}, function (errUser, userDoc){
if ( ! errUser ) {
fileDoc.user = userDoc;
}
});
}
});
but this code is not assigning the user to all files doc and only assigns to the last element of the filesDoc array. Any suggestions?
MongoDB doesn't support joins so you have to query for the User details separately. If you're using node.js, Mongoose provides a populate feature to help simplify this so you can do something like the following to pull in the user details:
Files.find().populate('Users_id')
I managed to find the cause of the issue. The reason why my code returns a null user is because I saved File.Users_id as String and I am retrieving it using ObjectId.
I fixed my codes by converting Users_id String to ObjectId before saving the File.
I have nodes like this:
[_id] => MongoId Object (
[$id] => 4e90cb3cd68417740c000017
)
[label] => mystery
[owner] => me
[parents] => Array (
[0] => Array (
[id] => MongoId Object (
[$id] => 4e8c6bb6d68417340e0004ca
)
[owner] => userid
[timestamp] => 1318112522
)
)
[timestamp] => 1318112060
[translabel] => mystery
[type] => 0
What I am trying to do is to remove parents with id : 4e8c6bb6d68417340e0004ca , wherever they are.
For example this should have been working (latest Mongo):
db.nodes.update({},{$pull : {"parents": { "id" : ObjectId("4e8c6bb6d68417340e0004ca") }}});
or equaly in PHP (latest driver etc):
$mongodb->nodes->update(array(),array('$pull'=> array('parents'=>array('id'=> new MongoId("4e8c6bb6d68417340e0004ca")))));
both don't do anything!
on the other hand:
db.nodes.update({"_id": ObjectId("4e90cb3cd68417740c000017")},{$pull : {"parents": { "id" : ObjectId("4e8c6bb6d68417340e0004ca") }}});
or equaly in PHP:
$mongodb->nodes->update(array('_id' => new MongoId("4e90cb3cd68417740c000017"),array('$pull'=> array('parents'=>array('id'=> new MongoId("4e8c6bb6d68417340e0004ca")))));
work perfectly well! Is this a bug? Is it a problem that I use "id" instead of "_id" with MongoID objects in my subdocuments? Thanks in advance for any help!
Have you tried enable multi flag on update command
db.collection.update( criteria, objNew, upsert, multi )
multi - indicates if all documents matching criteria should be updated rather than just one. Can be useful with the $ operators below.
and change your query to
db.nodes.update({},{$pull : {"parents": { "id" : ObjectId("4e8c6bb6d68417340e0004ca") }}},false,true);
or
db.nodes.update({ "_id" : { $exists : true } },{$pull : {"parents": { "id" : ObjectId("4e8c6bb6d68417340e0004ca") }}},false,true);
i haven't tested the code myself, but am sure that any one of the above will work..
I have two problem : How can I get affected rows by php mongodb driver ,and how about the last insert id ? thanks .
You can get number of results right from the cursor using count function:
$collection->find()->count();
You can even get number of all records in collection using:
$collection->count();
Using insert method, _id is added to input array automatically.
$a = array('x' => 1);
$collection->insert($a,array('safe'=>true));
var_dump($a);
array(2) {
["x"]=>
int(1)
["_id"]=>
object(MongoId)#4 (0) {
}
}
I don't believe that there is any type of affected_rows() method at your disposal with mongodb. As for the last insert _id You can generate them in your application code and include them in your insert, so there's really no need for any mysql like insert_id() method.
$id = new MongoId();
$collection->insert(array('
'_id' => $id,
'username' => 'username',
'email' => 'johndoe#gmail.com'
'));
Now you can use the object stored in $id however you wish.
Maybe MongoDB::lastError is what you are looking for:
(http://php.net/manual/en/mongodb.lasterror.php)
It calls the getLastError command:
(http://www.mongodb.org/display/DOCS/getLastError+Command)
which returns, among other things:
n - if an update was done, this is the number of documents updated.
For number of affected rows:
$status = $collection->update( $criteria, array( '$set' => $data ) );
$status['n']; // 'n' is the number of affected rows
If you have the output of your action, you can call relative function:
// $m hold mongo library object
$output = $m->myCollection->updateOne([
'_id' => myMongoCreateID('56ce2e90c9c037dba19c3ce1')], [
'$set' => ['column' => 'value']
]);
// get number of modified records
$count = $output->getModifiedCount();
$output is of of type MongoDB\UpdateResult. Relatively check following files to figure out the best function to find inserted, deleted, matched or whatever result you need:
https://github.com/mongodb/mongo-php-library/blob/master/src/InsertManyResult.php
https://github.com/mongodb/mongo-php-library/blob/master/src/DeleteResult.php
https://github.com/mongodb/mongo-php-library/blob/master/src/InsertOneResult.php
https://github.com/mongodb/mongo-php-library/blob/master/src/UpdateResult.php