【问题标题】:Getting a distinct aggregation elements of array by index通过索引获取数组的不同聚合元素
【发布时间】:2015-11-14 05:39:55
【问题描述】:
client = MongoClient()
db = client['test']
connection = db['test']
conn.insert({"tags": ["first_1", "second_1"]})
conn.insert({"tags": ["first_2", "second_1"]})
conn.insert({"tags": ["first_3", "second_2"]})
print conn.distinct("tags")

我得到了输出:

[u'first_1', u'second_1', u'first_2', u'first_3', u'second_2']

如何仅对数组的第二个元素执行此操作?我需要类似的东西:

[u'second_1', u'second_2']

【问题讨论】:

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


    【解决方案1】:

    根据docs$elemMatch$slice$ 是投影数组部分的唯一方法。将来我们可以在aggregate 中获得$slice 功能,详见this answer。但是现在我们没有直接的方法可以只使用 mongo 查询。
    工作代码:

    position = 1
    field = "tags"
    # see https://stackoverflow.com/a/15798087/4249707
    # for "not_existent_field" explanation
    results = conn.find(
      {}, {field:{"$slice": [position,1]}, "_id": 0, "not_existent_field": 1}
    )
    distinct_results = {d[field][0] for d in results if field in d and d[field]}
    

    【讨论】:

      猜你喜欢
      • 2019-05-26
      • 2012-08-24
      • 2020-01-02
      • 1970-01-01
      • 1970-01-01
      • 2013-12-03
      • 2022-06-27
      • 1970-01-01
      相关资源
      最近更新 更多