Mongodb复杂对象查询

我想从包含下面提到的对象的集合中find不同的城市值:

{ location:{ address:'XYZ', city:'New York' } } 

你能帮我解决我需要的问题吗? 我知道我必须使用elemMatch$exists 。 但我的下面的查询似乎工作,并返回一个空集:

 db.collectionName.distinct({'location':{'city':{$exists: true}}}) 

db.collection.distinct将查询作为第二个参数。

以下是你应该如何做的:

 db.collectionName.distinct('location.city', {'location.city': {$exists: true}}) 

另外,你也可以使用这个distinct数据库命令:

 db.runCommand({ "distinct": "collectionName", "key": "location.city", "query": {'location.city' : {$exists: true}} }).values 

db.collectionName.distinct('location.city')应该做的伎俩。