从mongo集合中选择特定字段不起作用

时间:2019-05-16 16:58:13

标签: mongodb aggregation-framework pymongo python-3.7

我有一个名为tabelas with data的收藏,例如:

{ "_id" : ObjectId("5cdcd4669dc6d6274f2234dc"), 
  "id" :  "recdj5bcTznLBGtbY", 
  "fields" : { "id_tabela" : "tab0005" }, 
  "createdTime" : "2018-08-13T19:15:26.000Z" }

我试图创建一个仅包含"id_tabela"给出的值的数组,在这种情况下,我的结果将是["tab0005"]

我尝试过,使用pymongo首先获取"fields"值,然后再获取id_tabela值。但是我什至没有得到fields值。

tabelas = db.get_collection("tabelas")
db.drop_collection("tabelas")
result_tabelas = tabelas.insert_many(lista_tabs)

tabelas = db.get_collection("tabelas") 
tab_array = list(tabelas.find())

vec_fields = tab_array['fields']

最后一行导致以下错误:

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: list indices must be integers or slices, not str

1 个答案:

答案 0 :(得分:1)

您也可以使用aggregation

db.collection.aggregate([
  { "$group": {
    "_id": False,
    "array": {
      "$addToSet": "$fields.id_tabela"
    }
  }}
])