2

我正在使用 monogdb 进行分配,我遇到了以下问题:返回的文档与返回的文档pymongo不匹配mongoc。一个简单的test.py

from pymongo import MongoClient
from bson.objectid import ObjectId

client = MongoClient()
db = client['dev_database']
print db.trials.find_one(ObjectId('522f975dc91e273451569942'))
print list(db.trials.find({'_id':ObjectId('522f975dc91e273451569942')}))

以防万一。这将返回:

{u'nurse_id': u'522f975dc91e273451569941', u'question_ids': [], u'name': u'Test Trial', u'clinician_id': u'522f975dc91e273451569940', u'arms': {u'Med1': u'', u'Placebo': u''}, u'participant_ids': [], u'keywords': [u'abc', u'123'], u'_id': ObjectId('522f975dc91e273451569942')}
[{u'nurse_id': u'522f975dc91e273451569941', u'question_ids': [], u'name': u'Test Trial', u'clinician_id': u'522f975dc91e273451569940', u'arms': {u'Med1': u'', u'Placebo': u''}, u'participant_ids': [], u'keywords': [u'abc', u'123'], u'_id': ObjectId('522f975dc91e273451569942')}]

如果我在 MongoDB Shell 中做同样的事情:

> use dev_database
switched to db dev_database
> db.trials.find('522f975dc91e273451569942')
{ "_id" : "522f975dc91e273451569942", "nurse_id" : "522f975dc91e273451569941", "question_ids" : [ ], "name" : "Test Trial", "clinician_id" : "522f975dc91e273451569940", "arms" : { "Med1" : "", "Placebo" : "" }, "participant_ids" : [
        "52325b93c91e274e81f4bdda",
        "52325b93c91e274e81f4bddb",
        "52325b93c91e274e81f4bddc",
        "52325b93c91e274e81f4bddd",
        "52325b93c91e274e81f4bdde"
], "keywords" : [ "abc", "123" ] }
>

如您所见,test.py返回一个participant_ids空列表的文档,但 MongoDB Shell 另有说明。

我不知道为什么会这样,而且似乎我一定是在某个地方犯了一个简单但根本性的错误。

4

2 回答 2

2

问题原来是我的代码保存了该文档的副本,该文档_id的类型为str. 例如

> db.trials.find()
{ "_id" : ObjectId("522f975dc91e273451569942"), "nurse_id" : "522f975dc91e273451569941", "question_ids" : [ ], "name" : "Test Trial", "clinician_id" : "522f975dc91e273451569940", "arms" : { "Med1" : "", "Placebo" : "" }, "participant_ids" : [ ], "keywords" : [ "abc", "123" ] }
{ "_id" : "522f975dc91e273451569942", "nurse_id" : "522f975dc91e273451569941", "question_ids" : [ ], "name" : "Test Trial", "clinician_id" : "522f975dc91e273451569940", "arms" : { "Med1" : "", "Placebo" : "" }, "participant_ids" : [
        "52325b93c91e274e81f4bdda",
        "52325b93c91e274e81f4bddb",
        "52325b93c91e274e81f4bddc",
        "52325b93c91e274e81f4bddd",
        "52325b93c91e274e81f4bdde"
], "keywords" : [ "abc", "123" ] }

MongoDB Shell 总是返回第二个结果,而测试代码返回第一个。不同之处在于我的代码显式转换为ObjectId,而 MongoDB Shell 似乎很乐意尝试使用strfirst 找到匹配项。

ObjectId(...)MongoDB Shell 的结果缺乏该领域的事实_id应该警告我有些不对劲。

于 2013-09-13T09:38:03.260 回答
0

下一个代码的输出是什么?

from pymongo import MongoClient
from bson.objectid import ObjectId

client = MongoClient()
db = client['dev_database']
print json.dumps(db.trials.find_one(ObjectId('522f975dc91e273451569942')))
于 2013-09-13T01:17:47.790 回答