Mongo

Serialize mongo objects

See what the json for a mongo object looks like

import static org.springframework.data.mongodb.core.query.SerializationUtils.serializeToJsonSafely;

@Test
public void serializeAggregation() {
  Aggregation aggregation = Aggregation.newAggregation(MyObject.class,
  ...,...);
  DBObject dbObject = aggregation.toDbObject("myCollection", Aggregation.DEFAULT_CONTEXT);
  System.out.println(serializeToJsonSafely(dbObject));
 }

loop through all databases

You can use db.getSiblingDB() to switch between databases and db.getCollectionNames() to get the collection names. Note that you have to run the first command from the admin database in order to get the list of databases. A short script in the shell to achieve what you want to do would look something like the following:1

db = db.getSiblingDB('admin');
dbs = db.runCommand({'listDatabases': 1}).databases;
dbs.forEach(function (database) {
    print(database.name);
})

forEach and findOne

Find entries in collection one that do not exist in collection two.

db = db.getSiblingDB('admin');
dbs = db.runCommand({'listDatabases': 1}).databases;
dbs.forEach(function (database) {
        db = db.getSiblingDB(database.name);
        db.collectionOne.find({}, {_id: 0, playerId: 1}).forEach(
            function (player) {
                snapshot = db.collectionTwo.findOne({'stateKey': player.playerId})
                if (!snapshot) {
                    print('use ' + database.name + '; db.collectionOne.deleteOne({ \u0027playerId\u0027:\u0027' + player.playerId + '\u0027})');
                }
            }
        )
    }
)

\u0027 represents the unicode for apostrophe.

1. Iterate over all Mongo database, by Juan Carlos Farah on Apr 13 2015

Last updated