1

I imported a json file into my database, and the db itself works.

If use

print db.points.find_one()

my output looks like :

{u'id': u'342902', u'_id': ObjectId('555af76a029d3b1b0ff9a4be'), u'type': u'node', u'pos': [48.9979746, 8.3719741], u'created': {u'changeset': u'7105928', u'version': u'4', u'uid': u'163673', u'timestamp': u'2011-01-27T18:05:54Z', u'user': u'Free_Jan'}}

which is exactly what I want it to be. But if I want to get the number of distinct users:

print db.points.distinct({"created.user"}).length

I get the error:

TypeError: key must be an instance of basestring

which suggests that what I was searching for is not there (it clearly is as shown above). What am I missing here ?

chridam
  • 100,957
  • 23
  • 236
  • 235
hmmmbob
  • 1,167
  • 5
  • 19
  • 33

2 Answers2

0

You have a syntax error in your distinct clause - it should be .distinct("created.user") instead of .distinct({"created.user"}).

See the MongoDB documentation for distinct.

Edit: To return the length, therefore, something like:

print len(db.points.distinct("created.user"));

... or:

print db.points.distinct("created.user").__len__();

See this answer for getting the size of a list in Python.

Caveat: I'm no Python expert so the length bit might not be perfect...

Community
  • 1
  • 1
Mark Hughes
  • 7,264
  • 1
  • 33
  • 37
  • Hhmm i changed it , according to your suggestion ( thank you by the way) , now i get a different error : AttributeError: 'list' object has no attribute 'length' – hmmmbob May 19 '15 at 13:51
  • I'm no expert at Python but I believe you need something like __len__() rather than .length. Editing to that effect. – Mark Hughes May 19 '15 at 13:57
0

I was facing the same problem.

print len(db.points.distinct("created.user")) works.

However, print db.points.distinct("created.user").__len__(); does not.

The reason for the error is the braces:

db.points.distinct({"created.user"})

should read

db.points.distinct("created.user") Also, '.length' is a mongo bash method. In pymongo, you use 'len()'. That is:

db.points.distinct({"created.user"}).length should read

print len(db.points.distinct("created.user")) unless you are using mongo bash/shell.