"MongoDB: Retrieve IP Address in a Flash"
When working with MongoDB, retrieving the IP address of the host machine or connected clients is a common requirement — whether for security auditing, connection monitoring, or troubleshooting network issues. Understanding how to correctly obtain and filter by IP address within MongoDB involves using built-in functions and querying connection metadata. This guide walks through the key methods to retrieve IP information effectively.

Using connectionStatus Command

One of the most direct ways to get client IP addresses is via the db.serverStatus() or db.currentOp() commands. However, for specifically targeting connected clients' IPs, the db.adminCommand({ connectionStatus: 1 }) is not the correct path. Instead, use the following approach.
1. db.currentOp() with client field

The db.currentOp() method provides details about current operations, including the client's IP address. Filter for active operations and extract the client field.
Here's an example query to list distinct client IPs of currently connected clients:

db.currentOp(true).inprog.forEach(function(op) {
if (op.client) {
print(op.client.split(':')[0]);
}
});
This script outputs just the IP addresses of active connections. For historical or authenticated user IPs, additional steps are required.
2. db.system.users.find() with credentials field
Direct IP storage isn't typical, but custom apps might store user and IP data. Query db.system.users.find() to retrieve user credentials, including custom fields like lastLoginIp.

db.system.users.find({}, {user: 1, credentials: 1, customData: 1});
Always respect privacy and security when accessing credential-related data. Use this for auditing only when necessary.
3. db.adminCommand({ serverStatus: 1 })
For server-level network statistics, including listening IPs:

var status = db.adminCommand({ serverStatus: 1 });
printjson(status.connections);
This returns active connections and listening addresses, but not individual client IPs.
Enabling IP Auditing with MongoDB Enterprise

.jpg)











MongoDB Enterprise includes native auditing. Configure it to log IP addresses:
- Set
auditLog.filterto capture client IPs. - Query the audit log:
db.adminCommand({ getLog: 'global' }); // Then filter for 'clientAddr' entries
This provides detailed connection events with IPs.
Security Best Practices
When dealing with IP addresses:
- Restrict access to administrative commands.
- Use TLS for encrypted connections.
- Rotate credentials regularly.
- Network segmentation to isolate database traffic.
Common Issues and Fixes
If IP retrieval seems off:
- Verify user roles — only admins can run
currentOp. - Check MongoDB version — Enterprise has more features.
- Use
db.runCommand({ connectionStatus: 1 })for a lightweight check.
Conclusion
Retrieving IP addresses in MongoDB is achievable through command-line tools and careful querying. Always balance functionality with security to maintain a robust, auditable system.