mongo 中的示例文档如下所示,但是我的集合有几千个文档,其中一些具有以下所有测试,有些仅具有以下测试的子集:
{
"_id" : ObjectId("52435f0f6f73205f7d37a2b0"),
"ID" : {
"schoolID" : "1234"
},
"institution" : {
"tests" : [
{
"test" : "SAT Math",
"25th_percentile" : null,
"mean" : 404,
"50th_percentile" : null,
"75th_percentile" : null
},
{
"test" : "SAT Verbal",
"25th_percentile" : null,
"mean" : 355,
"50th_percentile" : null,
"75th_percentile" : null
},
{
"test" : "SAT Writing",
"25th_percentile" : null,
"mean" : 363,
"50th_percentile" : null,
"75th_percentile" : null
},
{
"test" : "SAT Composite",
"25th_percentile" : null,
"mean" : 1122,
"50th_percentile" : null,
"75th_percentile" : null
},
{
"test" : "ACT Math",
"25th_percentile" : null,
"mean" : null,
"50th_percentile" : null,
"75th_percentile" : null
},
{
"test" : "ACT English",
"25th_percentile" : null,
"mean" : null,
"50th_percentile" : null,
"75th_percentile" : null
},
{
"test" : "ACT Reading",
"25th_percentile" : null,
"mean" : null,
"50th_percentile" : null,
"75th_percentile" : null
},
{
"test" : "ACT Science",
"25th_percentile" : null,
"mean" : null,
"50th_percentile" : null,
"75th_percentile" : null
},
{
"test" : "ACT Composite",
"25th_percentile" : null,
"mean" : null,
"50th_percentile" : null,
"75th_percentile" : null
}
]
}
}
我目前收到了几所学校的单独数据,想要更新文档,其中 ID 为“schoolID”,“test”为“ACT Composite”,“mean”为空。
我已经尝试过以下方法:
db.collection.update({$and:[{"ID.schoolID":"1234"}, {"institution.tests.$.test": "ACT Composite"}, {"institution.tests.$.mean": null}]}, {"$set":{"institution.tests.$.mean":"trial"}})
但是,该对象并未更新。
我也尝试过使用 $elemMatch:
db.collection.update({$and:[{"ID.schoolID":"1234"},{"institution.tests": {$elemMatch:{"test": "ACT Composite", "mean":null}}}]},{"institution.tests.$.mean":"trial"})
当使用 $elemMatch 时,我能够获得符合此条件的文档数量:
db.collection.find({"institution.tests":{$elemMatch:{"test":"ACT Composite", "mean":null}}}).count()
最后,我还尝试使用 pymongo 编写一个 python 脚本,它将对象转换为 pandas 数据框(因为我更熟悉如何使用数据框和“ifelse”在 R 中执行此操作,但是,我只遇到了麻烦更新特定对象,其中“test”为“ACT Composite”且“mean”为空。
任何帮助将不胜感激!
先感谢您!