# 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)


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://www.null-pointer.co.uk/mongo.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
