I have the following command for mongodb
db.products.find().forEach(
function(x) {
db.autocomplete.insert({
"_id": x.name
});
db.autocomplete.insert({
"_id": x.author_name
});
}
);
Which basically creates a collection for Autocomplete/Autosuggest words.
How can I run this command with PHP? There is no build in function to du forEach commands over the library.
I know, that there is http://php.net/manual/de/mongodb.command.php, but I do not understand, how to run above command in an array structure
I haven't tested it, but it must be something like this:
$q = new MongoDB\Driver\Command([
'mapreduce' => 'products',
'map' => 'function () { emit(this.name, 1); emit(this.author_name, 1);}',
'reduce' => 'function () { return null; }',
'finalize' => 'function () {return null}',
'out' => ['reduce' => 'autocomplete']
]);
map
emits both name and author_name as keys with arbitrary value. reduce
returns null, as we don't care about values. finalize
is optional. It ensures values are null. Otherwise it may contain some residual junk.