简体   繁体   English

pyMongo迭代带有子项的光标对象

[英]pyMongo iterate over cursor object with subitems

The function below searches a collection with a subitem projects. 下面的函数搜索带有子项目项目的集合。 If there is a subitem with isManager set to 1 it should return True otherwise it will always return False . 如果isManager设置为1的子项目,则应返回True否则将始终返回False

def isMasterProject(self, pid, uid):
  masterProjects = False
  proj = self.collection.find({ "_id": uid, "projects": { '$elemMatch': { "projectId": _byid(pid), "isManager": 1 } } })
  for value in proj:
    if str(value['projects']['projectId']) == pid:
      if value['projects']['isManager'] == 1:
        masterProjects = True
  return masterProjects

_byid is equivalent to ObjectId _byid等效于ObjectId

It always seem to return False . 它似乎总是返回False Here's an example of a collection. 这是一个集合的例子。

{
  "_id" : ObjectId("52cf683306bcfc7be96a4d89"),
  "firstName" : "Test",
  "lastName" : "User",
  "projects" : [
    {
      "projectId" : ObjectId("514f593c06bcfc1e96f619be"),
      "isManager" : 0
    },
    {
      "projectId" : ObjectId("511e3ed0909706a6a188953d"),
      "isManager" : 1
    },
    {
      "projectId" : ObjectId("51803baf06bcfc149116bf62"),
      "isManager" : 1
    },
    {
      "projectId" : ObjectId("514362bf121f92fb6867e58f"),
      "isManager" : 1
    }
  ],
  "user" : "test.user@example.com",
  "userType" : "Basic"
}

Would it be simpler to check for an empty cursor and if so how would I do that? 检查空的游标会更简单吗,如果是的话,我该怎么做?

How about: 怎么样:

obj = next(proj, None)
if obj:

$elemMatch should only return results if the criteria given match a document so you should only return a cursor from find where your criteria are true. $ elemMatch仅在给定的条件与文档匹配时才返回结果,因此您仅应从找到条件为真的位置返回游标。

Since you are using _id in the query and only ever expect to get one result, why not use findOne and shortcut one step. 由于您在查询中使用_id并且只希望得到一个结果,所以为什么不使用findOne和捷径一步。

Another gotcha for the new initiates, be aware you are returning the whole document here and not some representation with only the matching element of the array. 新手的另一个陷阱 ,请注意,您将在此处返回整个文档,而不是仅包含数组匹配元素的某些表示形式。 Things that did not match will still be there, and then expecting different results by iterating over these will lead you to grief. 不匹配的事物将仍然存在,然后通过迭代这些期望不同的结果将使您感到悲伤。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM