我正在尝试在我的集合中的数组中进行搜索,以通过名为“id”的键进行查找。 find() 方法和 find_one_and_update() 都不会返回我试图查找的条目。该集合的结构如下:
"_id" : {stuff},
"events":[{
"id":"12345",
"date":"01/01"
}, {
"id":"12346",
"date":"02/02"
}]
尝试 find() 为:
result = db.get_collection("events").find({"events.id" : "12345"})
for item in result:
print(item)
打印整个集合。 尝试通过 ID 更新特定条目,就像这样会将其附加到末尾。
db.get_collection("events").find_one_and_update({"events.id" : "12345"},{"$set" : {"date" : "somedate"}})
之后看起来像这样:
"id":"12346",
"date":"02/02"
}], "date" : "somedate"
那么,我在这里更新和查找做错了什么?其他人似乎都对这部分没有任何问题。
我自己解决了这个问题,需要指定要在集合中更新哪个对象+字段:
db.get_collection("events").find_one_and_update({"events.id" : "12345"},{"$set" : {"events.$.date" : "somedate"}})