w3resource

How to Retrieve all Unique Key Names in a MongoDB Collection

Get all Unique Key Names in MongoDB Collection

In MongoDB, retrieving the names of all unique keys (or fields) in a collection is not a built-in feature, but you can achieve this by aggregating data to gather a list of keys. This can be done by leveraging MongoDB's $project and $objectToArray operators, which help convert document fields into an array format and collect all distinct keys.

Description:

To retrieve all unique key names in a MongoDB collection, you can use an aggregation pipeline. By converting documents into key-value arrays, you can collect and deduplicate key names across all documents in a collection. This approach is useful for understanding the structure of your data or when working with schema-less collections.

Syntax:

You can get all unique keys in a collection using an aggregation pipeline:

Syntax:

db.<collection>.aggregate([
  { $project: { keys: { $objectToArray: "$$ROOT" } } },
  { $unwind: "$keys" },
  { $group: { _id: null, allKeys: { $addToSet: "$keys.k" } } },
  { $project: { _id: 0, allKeys: 1 } }
])
  • <collection>: The name of the collection from which you want to get the key names.

Example:

Suppose you have a students collection and want to retrieve all unique keys in the collection:

Code:

 // Use an aggregation pipeline to get names of all unique keys in the 'students' collection
db.students.aggregate([
  // Convert each document's fields to key-value pairs
  { $project: { keys: { $objectToArray: "$$ROOT" } } },
  
  // Unwind the array to get each key individually
  { $unwind: "$keys" },
  
  // Group all keys and add them to a set to ensure uniqueness
  { $group: { _id: null, allKeys: { $addToSet: "$keys.k" } } },
  
  // Project only the 'allKeys' array in the output
  { $project: { _id: 0, allKeys: 1 } }
])

Explanation:

  • . $project: { keys: { $objectToArray: "$$ROOT" } }
    • The $project stage creates a new keys field that converts each document’s fields to an array of key-value pairs using $objectToArray.
    • $$ROOT represents the entire document, so all fields are included in the keys array.
  • $unwind: "$keys"
    • The $unwind stage deconstructs the keys array so each key-value pair appears as a separate document in the pipeline. This allows us to work with each key individually.
  • $group: { _id: null, allKeys: { $addToSet: "$keys.k" } }
    • The $group stage collects all unique key names into an array allKeys.
    • $addToSet ensures that each key is added only once, removing duplicates across documents.
  • $project: { _id: 0, allKeys: 1 }
    • Finally, the $project stage removes the _id field from the output, displaying only the allKeys array.

This aggregation pipeline will return an array containing the names of all unique keys present in the students collection.

Additional Notes:

Dynamic Fields: MongoDB is schema-less, so documents in the same collection can have different keys. This method is particularly useful when dealing with collections where fields vary significantly between documents.

Performance: For very large collections, this operation can be resource-intensive, as it needs to examine every document to collect keys.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/mongodb/snippets/how-to-retrieve-all-unique-key-names-in-a-mongodb-collection.php