【问题标题】:How to get one field value in Mongodb collection如何在Mongodb集合中获取一个字段值
【发布时间】:2020-04-30 21:34:06
【问题描述】:

我想在 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}

我正在尝试这个查询:

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

我得到这样的输出

<pymongo.cursor.Cursor object at 0x000002120610EF98>

【问题讨论】:

  • x = mydb.mycollection.distinct("Date") 像这样使用
  • 谢谢你。但是这个逻辑得到了一个空列表[]
  • 空数组表示没有数据!!!!!!
  • 是否有数据意味着输出将是 [ 10-01-2020, 11-01-2020, 14-01-2020 ]

标签: mongodb mongoose mongodb-query pymongo pymongo-3.x


【解决方案1】:

基本上.find() 会返回一个游标——这就是为什么你的print(x) 的输出是&lt;pymongo.cursor.Cursor object at 0x000002120610EF98&gt;,你需要遍历以访问其中的文档,另外我在投影中添加了_id:0 按顺序明确排除 _id 字段,默认情况下包含该字段。这个 for 循环将打印 x 的值,直到光标用尽,试试这个:

for x in mydb.mycollection.find({}, {_id :0, "Date": 1}):
  print(x)

如果您需要不同的日期值:

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

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      【解决方案3】:
      mydb.mycollection.find({}, {"Date": 1})
      

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

      【讨论】:

      • 这正是 OP 正在做的事情,并且已经在问题中提到过,不幸的是,这不需要作为答案,问题完全不同,他希望它可以被访问或打印 :-) ! !
      【解决方案4】:
      my_cursor = mydb.mycollection.find()
      for x in my_cursor:
          print('{0}'.format(x['Date']))
      

      【讨论】:

      • 见“Explaining entirely code-based answers”。虽然这在技术上可能是正确的,但它并不能解释为什么它可以解决问题或应该是选择的答案。除了帮助解决问题,我们还应该进行教育。
      猜你喜欢
      • 1970-01-01
      • 2018-10-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-13
      • 2017-01-01
      • 2023-03-26
      相关资源
      最近更新 更多