> For the complete documentation index, see [llms.txt](https://www.null-pointer.co.uk/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://www.null-pointer.co.uk/mongo.md).

# Mongo

### Serialize mongo objects <a href="#serialize-mongo-objects" id="serialize-mongo-objects"></a>

See what the json for a mongo object looks like

```java
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 <a href="#loop-through-all-databases" id="loop-through-all-databases"></a>

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](https://www.null-pointer.co.uk/mongo.html#fn_1)

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

### forEach and findOne <a href="#foreach-and-findone" id="foreach-and-findone"></a>

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

```javascript
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](https://stackoverflow.com/questions/29609667/iterate-over-all-mongo-database), by Juan Carlos Farah on Apr 13 2015[ ↩](https://www.null-pointer.co.uk/mongo.html#reffn_1)
