List Collection fields

Posted under » MongoDB on 7 Feb 2024

Mongodb makes it too convenient to create fields in your collections and you can give fanciful names too. However, it can get messy and you can't find the fields that you want.

To get fields that are indexed.

students> Object.keys(db.mth.findOne())
[ '_id', 'username', 'date_joined', 'cid' ]

If you want to list all fields.

db.mth.aggregate([
    { $project: { keys: { $objectToArray: "$$ROOT" } } },
    { $group: { _id: "$keys.k" } }])
	.forEach(function(doc) { print(doc._id); });

When you want to retrieve documents based on whether a field contains or does not contain data, you use the $exists operator.

db.mth.aggregate([
db.student.find({"age": {$exists: true}}, {"age": 1})

web security linux ubuntu python django git Raspberry apache mysql php drupal cake javascript css AWS data