我想从包含对象的集合中查找城市的不同值,如下所述:
{
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')
应该可以解决问题。