MongoDB – changing data directory name changes data

mongodb

I am witnessing a very bizzare behaviour of MongoDB.

I launch MongoD on a test system (Windows 10, 64bit) like this:

"C:\Program Files\MongoDB\Server\3.6\bin\mongod.exe" --dbpath "C:\MongoData"

I then shut down the server and replace the MongoData directory with a data set from a production server. I start mongod again, but I get a collection with 4 documents, which is what I used to have before I replaced my test data set with a real one.

That's not right, because I would expect to see loads of documents in a real data set. I then try dozens of things, including pointing MongoD to the data folder in its original location, which gives me all the documents from the real collection. Phew, the data is safe. But what is happening in my test system?

I have noticed that if I rename the folder in my test system to MongoData2 and lanuch mongod pointing at it then I get my proper production data set. but if I rename it back to MongoData and launch mongod pointing at this folder I get 4 documents again.

What is causing this?

Best Answer

As per MongoDB documentation here To use an alternate dbpath, specify the path in the configuration file (e.g. C:\mongodb\mongod.cfg) or on the command line with the --dbpath option.

Default: /data/db on Linux and macOS, \data\db on Windows

The directory where the mongod instance stores its data.

Changed in version 3.0: The files in --dbpath must correspond to the storage engine specified in --storageEngine. If the data files do not correspond to --storageEngine, mongod will refuse to start.

--directoryperdb

Uses a separate directory to store data for each database. The directories are under the --dbpath directory, and each subdirectory name corresponds to the database name.

Changed in version 3.0: To change the --directoryperdb option for existing deployments, you must restart the mongod instances with the new --directoryperdb value and a new data directory (--dbpath ), and then repopulate the data.

  • For standalone instances, you can use mongodump on the existing instance, stop the instance, restart with the new --directoryperdb value and a new data directory, and use mongorestore to populate the new data directory.
  • For replica sets, you can update in a rolling manner by stopping a secondary member, restart with the new --directoryperdb value and a new data directory, and use initial sync to populate the new data directory. To update all members, start with the secondary members first. Then step down the primary, and update the stepped-down member.