How to get _id MongoDB/php? - php

I do this way:
$cursorLocations = $collection->find( array("locationName" => $locationName) )->limit(1);
if ($cursorLocations->count(true) == 1) {
$idLocations = $cursorLocations->getNext();
echo $idLocations["_id"];
}
I immediately apologize if this question has been, but read the documentation did not find an answer.
Maybe some other way to get the _id?

in Mongo :
db.collection.find({'field': 'value'}, {'_id' : 1});
in PHP:
$cursorLocations = $collection->find( array("locationName" => $locationName), array('_id' => 1) )->limit(1);
The above code will limit your query to retrieving only the _id field and not the other fields, you would still have to extract the value of that field from the result of the find() function - from the $cursor object, like in:
$_id = $cursorLoactions[`_id`];
There is also a MongoCursor method key() which returns the current _id:
http://www.php.net/manual/en/mongocursor.key.php
So you could do this:
$cursorLocations = $collection->find( array("locationName" => $locationName) )->limit(1);
$_id = $cursorLocations->key();

Related

Check if collection exists in mongodb using MongoDB\Driver in PHP 7.1.6

I have searched for the answer without any results. I need to check if a Collection exists in my mongodatbase using MongoDB\Driver in PHP 7.1.6. Does anyone know how to do it? thanks.
I have done this method to verify if there exist a collection must pass the name, you will return 0 if it does not exist and 1 if it exists
public function verifyCollection($name){
$bd = $this->conexion->mongo();
$data = $bd->listCollections([
'filter' => [
'name' => $name,
],
]);
$exist = 0;
foreach ($data as $collectionInfo) {
$exist = 1;
}
return $exist;
}
Use db.getCollectionNames() and then test for existence of the collection you seek with indexOf() e.g.
idx = db.getCollectionNames().indexOf("myColl");
If idx = -1, then myColl does NOT exist. The equiv in perl would be
my #collections = $database->collection_names;
Then you can use smartmatch or grep or whatever you like to scan the collections list.
You can use listCollections() just remember it returns an object and not an array.
In the below code $collectionNames is an array of just the names.
$collections = $database->listCollections();
$collectionNames = [];
foreach ($collections as $collection) {
$collectionNames[] = $collection->getName();
}
Then check it like this:
$exists = in_array('some_collection', $collectionNames);
This worked for me. Basically you use listCollections() function, but it was not easy to figure out how to use it correctly in php-extension (thanks to #John56 for his answer in this thread). $manager is MongoDB\Driver\Manager class. Hope it helps you to save some time :)
$command = new Command(['listCollections' => 1, 'filter' => ['name' => 'collection-name']]);
$result = $manager->executeCommand('db-name', $command)->toArray();
if (false == empty($result) { whatever ...}
First create your mongo object here $mongodb_object
then
$collections = $mongodb_object->getCollectionNames();
The collections variable contains all the collection names as array
Return array example is given below
[0] => collection_name1
[1] => collection_name2
[2] => collection_name3

php mongoclient - trying to query records that only have a "department" field

I have made the following attempt to query documents that have a department value filled in:
$collection = $this->mongo_db->db->selectCollection('widget');
$result = $collection->find(
array("department"=>array('$ne' => null),"department"=> array('$ne' => ""))
)->sort(['department'=>1]);
return iterator_to_array($result);
But this is still returning documents that look like this:
{
"_id" : ObjectId("5824b9376b6347a422aae017"),
"widgetnum" : "1840023",
"last_assigned" : "missing"
}
I thought the
"department"=>array('$ne' => null)
would have filtered this out.
Any suggestions?
For you perfect will be $exists operator.
https://docs.mongodb.com/manual/reference/operator/query/exists/
Query should look something like this(select all documents where department exists and does not equal to "").
$collection = $this->mongo_db->db->selectCollection('widget');
$result = $collection->find(
array( "department"=> array('$exists' => "true", '$nin': [""]) )
)->sort(['department'=>1]);
return iterator_to_array($result);
Hope this helps.

MongoDB/PHP - MapReduce Max value

I used to group on mongoDB via PHP to get the max date of my items.
As i have too many items (more than 10 000), i read i must use MapReduce.
Here's my past group function :
$keys = array('ItemDate'=> true);
$initial = array('myLastDate' => 0);
$reduce = "function(obj, prev) {
if (myLastDate < obj.ItemDate) {
myLastDate = ItemDate;
}
}";
$conds = array( 'ItemID' => (int) $id );
$results = $db->items->group($keys, $initial, $reduce,
array('condition'=> $conds ) );
I've tried something but seems not to work ...
$map = new MongoCode("function() {
emit(this.ItemID,this.ItemDate);
}");
$reduce = new MongoCode("function(obj, prev) {
if(prev.myLastDate < obj.ItemDate) {
prev.myLastDate = obj.ItemDate;
}
}");
$items = $db->command(array(
"mapreduce" => "items",
"map" => $map,
"reduce" => $reduce,
"query" => array("ItemID" => $id);
$results = $db->selectCollection($items['result'])->find();
Can you please help ?
Solution
You don't need to use map/reduce for that. Provided your date field contains an ISODate, a simple query does the trick:
db.yourColl.find({},{_id:0,ItemDate:1}).sort({ItemDate:-1}).limit(1)
In order to have this query done efficiently, you need to set an index on ItemDate
db.yourColl.createIndex({ItemDate:-1})
Explanation
The query
Let us dissect the query. db.yourColl...
.find({} The default query
,{_id:0,ItemDate:1} We want only ItemDate to be returned. This is called a projection.
.sort({ItemDate:-1}) The documents returned should be sorted in descending order on ItemDate, making the document with the newest date the first to be returned.
.limit(1) And since we only want the newest, we limit the result set to it.
The index
We create the index in descending order, since this is the way you are going to use it. However, if you need to change the default query to something else, the index you create should include all fields you inspect in the query, in the exact order.

Find entity by id column, \Phalcon\Mvc\Model::findFirst() gives incorrect result

Currently i have table with posts, each posts has an id.
For a moment, only one posts exists, with id id = 92.
if i execute following code, i will get not false, but post with id=92:
$post = NewsPost::findFirst(['id' => 1]);
var_dump($post->id); // gives 92
Seems to be very strange logic..
What method could be used to retrieve post by id, and that will return false/throw exception if there is no such entity?
Try this:
$post = NewsPost::findFirst("id = 1");
or
$post = NewsPost::find(
array(
"conditions" => "id = ?0",
"bind" => array(0 => 1)
)
);
I use:
$instance = Model::findFirst($id);
Where $id is a primary key.
Use
NewsPost::findFirst(['id = 1']);
or
NewsPost::findFirst(1)
You should use:
NewsPost::findByid(1);
Where 'id' can be replaced by any of your model's properties. For example:
NewsPost::findByDescription('Description');
NewsPost::findByyourprop(yourpropval);
You can then count() the return value count($result) to determine if you received any records.
Note: I have also found the string searches to be case in-sensitive.

Symfony2 's mongoDB returns a loggablecursor instead of my entities

I currently use the DoctrineMongoDbBundle to make requests the my mongodb database.
Here's the call in my controller:
$dm = $this->get('doctrine.odm.mongodb.document_manager');
$entities = $dm->getRepository('MyBundle:Animal')->findBy(array("prop" => "1"));
echo print_r($entities->getQuery());
echo printf(count($entities));
echo get_class($entities);
Then I tried to serialize $enitities to json and send it to the client but it didnt work.
The echos printed:
Array ( [prop] => 1 )
101
Doctrine\ODM\MongoDB\LoggableCursor0
It means that the query is correct but the count should be "2" and the type should be an Animal array.
Why is the reposity returning a LoggableCursor0 instead of an Animal array?
[edit]
How could it return an Animal array?
[edit] What would be the best way to return my result in JSON?
Use method toArray(). Like this:
$dm = $this->get('doctrine.odm.mongodb.document_manager');
$entities = $dm->getRepository('MyBundle:Animal')->findBy(array("prop" => "1"))->toArray();
If you need to get array of entities, use array_values() function. Like this:
$entities = array_values($entities);
findBy returns a Cursor in MongoDB ODM unlike doctrine orm.
Try:
echo printf($entities->count());
If you want a bit more flexibility when storing entities as an array you can do this
$dm = $this->get('doctrine.odm.mongodb.document_manager');
$animalLoggableCursors = $dm->getRepository('MyBundle:Animal')->findBy(array("prop" => "1"));
$animals = array()
while ($animal = $animalLoggableCursors->getNext()) {
if ($animal->getSomeProperty() == $someValue)
array_push($animals, $animal)
}

Categories