Get names of all keys in collection in MongoDB


You are here : Home / MongoDB Tutorial


Contents of page >
  • CASE 1: Get names of all keys in collection in MongoDB when all the documents contain same fields >
  • CASE 2: Get names of all keys in collection in MongoDB when documents contain different fields >

CASE 1: Get names of all keys in collection in MongoDB when all the documents contain same fields >


First, insert in collection in MongoDB.
> db.employee.insert({firstName:"ankit", lastName: "mittal" })
> db.employee.insert({firstName:"neha", lastName: "mittal" })
Above line will create collection(table) (if collection already exists it will insert records in it).

Now, we will find one document by using findOne() method and then display all its keys
> allKeys=db.employee.findOne();
for (key in allKeys){
print(key);
}


Output will be >
_id
firstName
lastName
All keys are displayed.



CASE 2: Get names of all keys in collection in MongoDB when documents contain different fields >


First, insert in collection in MongoDB.
> db.employee.insert({firstName:"ankit", lastName: "mittal" })
> db.employee.insert({salary:"1000" })

Now, we will find keys of all documents in variable allKeys by using MapReduce
> allKeys = db.runCommand({
 "mapreduce" : "employee",
 "map" : function() {
   for (var key in this){
emit(key, null);
}
 },
 "reduce" : function(key, value){
  return null;
 },
 "out": "employee"
})


Now, display all unique keys in allKeys >
> db[allKeys.result].distinct("_id")


Output will be >
[ "_id", "firstName", "lastName", "salary" ]
All distinct keys are daisplayed.


Summary -


So in this core java tutorial we learned get names of all keys in collection in MongoDB.

Having any doubt? or you liked the tutorial! Please comment in below section.
Please express your love by liking JavaMadeSoEasy.com (JMSE) on facebook, following on google+ or Twitter. You may join our fbGroup or linkedInGroup as well.


RELATED LINKS>


Using like statement (as in sql) in MongoDB

Update documents in collection in mongoDB



Delete documents in collection (table) in mongoDB

How to Delete all documents from collection in MongoDB


Labels: MongoDB
eEdit
Must read for you :