Category Archives: mongodb

Map invoke errors when using MongoDB MapReduce

When running MapReduce operations on your data, you must make sure that any fields you refer to within your map operation are available for every document in your collection. If you try a map operation and some documents do not have the required field, you will get the following assertion error when running the command:

map invoke failed: JS Error: TypeError: this.fieldname has no properties

fieldname in this case is a field that does not exist in all of the documents.

To prevent this error, you can pass the optional query parameter to the command to make sure that only documents with this field are queried. For example, in PHP, add the following to the command operation:


$db->command(
    'mapreduce' => 'collection',
    'map'       => $map,
    'reduce'    => $reduce,
    'out'       => array( 'inline' => 1 ),
    'query'     => array( "fieldname" => array( '$exists' => true, ) )
);

This makes sure that MapReduce operations are only run on a subset of the collection.

Glen Scott

I’m a freelance software developer with 18 years’ professional experience in web development. I specialise in creating tailor-made, web-based systems that can help your business run like clockwork. I am the Managing Director of Yellow Square Development.

More Posts

Follow Me:
TwitterFacebookLinkedIn

Exporting specific documents from MongoDB

Mongodb

MongoDB comes with a useful tool, mongoexport, for exporting collections. However, you can also use it to export specific documents by utilising the query parameter. You can export a single document using it’s ObjectId using a command similar to the following:

mongoexport -h "host_name" -u "username" -d "database_name" -c "collection_name" -q '{"_id":ObjectId("4f045677a1ef264746000011")}' -o output.js -p
  • Replace host_name, username, database_name and collection_name with the appropriate values.
  • Replace 4f045677a1ef264746000011 with the ObjectID that you wish to export

You will be prompted for a password, and then the document will be written to output.js.

To export multiple documents, you can utilise an $in clause in the query parameter like this:

-q '{"_id":{"$in" :[ ObjectId("4f048dc6a1ef26da4b000008"),ObjectId("4ed8ee16a1ef26085600001a"),ObjectId("4efc46e0a1ef26b73d0007be")]}}'

To import these exported documents into another MongoDB server, you can use the mongoimport like so:

mongoimport -h "host_name" -u "username" -p -d "database_name" -c "collection_name" output.js

Glen Scott

I’m a freelance software developer with 18 years’ professional experience in web development. I specialise in creating tailor-made, web-based systems that can help your business run like clockwork. I am the Managing Director of Yellow Square Development.

More Posts

Follow Me:
TwitterFacebookLinkedIn