gpt4 book ai didi

node.js - Mongodb 复杂对象查询

转载 作者:太空宇宙 更新时间:2023-11-03 22:55:48 25 4
gpt4 key购买 nike

我想从包含对象的集合中找到城市的不同值,如下所述:

{
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

关于node.js - Mongodb 复杂对象查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13909206/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com