MongoDB query for aggregate function retuning empty result - mongodb

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.

Related

Cast or convert mongodb _id object to string in Logstash pipeline

I am working on creating a pipeline to get data from MongoDB to ElasticSearch using Logstash.
I am using dbschema mongodb jdbc drivers. I am able to connect to database using driver but I am facing issue with _id . As in MongoDB its of type object So I am getting issue with converter. Here is error I am getting.
Exception when executing JDBC query {:exception=>#<Sequel::DatabaseError: Java::OrgLogstash::MissingConverterException: Missing Converter handling for full class name=org.bson.types.ObjectId, simple name=ObjectId>}
My pipeline is as below :
input{
jdbc{
jdbc_driver_library => "C:/logstash-6.1.0/logstash-6.1.0/bin/driver/mongo/dbschema/mongojdbc1.2.jar"
jdbc_driver_class => "Java::com.dbschema.MongoJdbcDriver"
jdbc_connection_string => "jdbc:mongodb://abc.com:27017/test"
jdbc_user => ""
statement => "db.getCollection('Employee').find({})"
codec => json
}
}
output {
elasticsearch {
hosts => 'http://localhost:9200'
index => 'mongodbschema'
codec => json
}
stdout { codec => rubydebug }
}
Is there any way I can convert/cast or do something in filter to change datatype of _id from object to string
try
statement => "db.getCollection('Employee').find({ },{'_id': false})"
Try this code in filter
filter {
mutate {
remove_field => [ "_id" ]
}}
Since in elasticsearch _id is a reserved field (you can pass _id to index API in PUT operation to update a document), you must apply a filter that mutates the mongodb _id, for instance:
filter {
mutate {
rename => [ "_id", "mongo_id" ]
}
}

Data type issue in aggregation in mongo db

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?

Find query with and operator in PHP

Hi i am working on backend of web application & want to find the documents from mongodb database that contain key active_status with value set to both 1 & 2. With mongodb PHP i am confused of how to find with both parameters in single query.
My query was this:
$mongoDb = MongoDbConnector::getCollection("endusers");
$endUserData = $mongoDb->find(array('active_status' => 1, '$and' => array('active_status' => 2)));
I have to fetch the users whose active_status should be 1 & 2. The above query doesnt seems to work. What is the right one for that?
Thanks on advance for quick response.
You have $and the wrong way around. Both arguments need to be included:
$endUserData = $mongoDb->find(array(
'$and' => array(
array( 'active_status' => 1 )
array( 'active_status' => 2 )
)
));
And since that would only make sense when looking for both elements within an array element, then you should instead use $all, which is shorter syntax:
$endUserData = $mongoDb->find(array(
'active_status' => array( '$all' => array(1,2) )
));
I should add that unless you intend to match a document like this:
{ "active_status" => [1,2] }
The you do not in fact want $and at all, but rather you want $or or better yet $in for multiple possible values on the same field:
$endUserData = $mongoDb->find(array(
'active_status' => array( '$in' => array(1,2) )
));
This matches documents like this:
{ "active_status": 1 },
{ "active_status": 2 }

or operation in yii mongo suite or direct mongo suite

I am having a problem with mongo db when used in yii framework. I tried both yii extensions yii mong suite and direct mongo suite. I have trouble implementing or operations in mongo with these extension. I used this code in yii mongo suite but its returning all the values.
$userDetail = $user->findAll(
array(
'$or' => array(
"first_name" => "akash",
"first_name" => "anoop"
)
)
); var_dump($userDetail);die;
I dont know how to use or operation with direct mongo suite. Please help me as soon as possible. Thank You.
With the direct MongoDBSuite, providing it implements MongoDB directly, your $or should look like:
$userDetail = $user->findAll(
array(
'$or' => array(
array("first_name" => "akash"),
array("first_name" => "anoop")
)
)
);
I know this is pretty late but let me know if this helps. I'm using YiiMongoDbSuite. You could check to see if the name is in an array.
$criteria = new EMongoCriteria;
$criteria->addCond("first_name","in",array("akash", "anoop"));
Read more here about using the EMongoCriteria Object: http://bit.ly/1oOFPBJ

How to get affected number of rows using mongodb ,php driver

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