如何在Mongodb集合中获取一个字段值

如何在Mongodb集合中获取一个字段值,mongodb,mongoose,mongodb-query,pymongo,pymongo-3.x,Mongodb,Mongoose,Mongodb Query,Pymongo,Pymongo 3.x,我想在MongoDb中获取mycollection中的所有日期 数据库名称为:mydb 集合名称:mycollection 文件1: "Date":"10-01-2020", "timeslot1":"11-12" ,"timeslot2":null ,"timeslot3":null ,"timeslot4":null 文件2: "Date":"11-01-2020", "timeslot1":null ,"timeslot2":null ,"timeslot3":null ,"time

我想在MongoDb中获取mycollection中的所有日期

数据库名称为:mydb

集合名称:mycollection

文件1:

"Date":"10-01-2020", "timeslot1":"11-12" ,"timeslot2":null ,"timeslot3":null ,"timeslot4":null 
文件2:

 "Date":"11-01-2020", "timeslot1":null ,"timeslot2":null ,"timeslot3":null ,"timeslot4":null 
文件3:

 "Date":"14-01-2020", "timeslot1":null ,"timeslot2":null ,"timeslot3":null ,"timeslot4":null
我想要所有的日期。我想要这样的输出

{10-01-2020, 11-01-2020, 14-01-2020}
<pymongo.cursor.Cursor object at 0x000002120610EF98>
我正在尝试以下查询:

x = mydb.mycollection.find({}, {"Date": 1})
  print(x)
我得到这样的输出

{10-01-2020, 11-01-2020, 14-01-2020}
<pymongo.cursor.Cursor object at 0x000002120610EF98>

基本上
.find()
会返回一个光标-这就是为什么
print(x)
的输出是
,您需要迭代访问其中的文档,而且我在投影中添加了
\u id:0
,以明确排除默认包含的
\u id
字段。此for循环将打印x的值,直到光标用尽为止,请尝试以下操作:

for x in mydb.mycollection.find({}, {_id :0, "Date": 1}):
  print(x)
如果您需要不同的日期值:

for x in mydb.mycollection.distinct('Date'):
    print(x)

您可以使用
list
将光标转换为list

x = mydb.mycollection.find({}, {"Date": 1})
y = list(x)

print(y)

如果您想从多个表中获取数据,那么应该使用聚合函数aity

x=mydb.mycollection.distinct(“日期”)这样使用谢谢vicky。但是逻辑是得到一个空列表[]空数组意味着没有数据!!!!!!是否有数据意味着输出将为[10-01-2020,11-01-2020,14-01-2020],这正是OP正在做的事情&已经在问题中提到过,不幸的是,这不需要回答,问题完全不同,他希望访问或打印:-!!见“”。虽然这在技术上可能是正确的,但它并没有解释为什么它解决了问题,或者应该是选择的答案。除了帮助解决问题外,我们还应该进行教育。
my_cursor = mydb.mycollection.find()
for x in my_cursor:
    print('{0}'.format(x['Date']))