0

I have installed MongoDB in my system and I inserted 10 documents into the username collection. That document contains name, roll no, city fields. I need to count the number of fields in the username collection.

I except 3... How to get the 3 from java program?

2 Answers 2

1

If you are using Java in your application you are manipulating DBObject ( http://api.mongodb.org/java/2.6/com/mongodb/DBObject.html ) and you can get the KeySet from this and the size will be the number of attributes. (in your case it will be 4 since you have the _id attribute)

But this is PER DOCUMENT, remember that in a collection, each document can have its own "structure", in your case one user could have 4 attributes, another could have 10... and some of them could have sub documents with their own structure. MongoDB does not have any "catalog".

Some system are "sampling" the data to analyze the global structure of the documents and provide a catalog but this is will not be exact.

Sign up to request clarification or add additional context in comments.

Comments

0

Try this:

System.out.println(coll.getCount());

More Detail here: http://docs.mongodb.org/ecosystem/tutorial/getting-started-with-java-driver/

1 Comment

System.out.println(coll.getCount()); this command only get the number of row in the db.. I got the solution cursor.next().toMap().keySet().size();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.