MongoDB:带有数组过滤器的UPSERT
我有这样的收藏:
mc.db.collection.insert_many([
{"key_array": [1], "another_array": ["a"]},
{"key_array": [2, 3], "another_array": ["b"]},
{"key_array": [4], "another_array": ["c", "d"]},
])
我正在使用这种更新:
mc.db.collection.update_one(
{"key_array": 5},
{"$addToSet": {"another_array": "f"}},
upsert=True
)
它可以在更新中效果很好,但是在尝试上升时我遇到了麻烦:
它创建一个使用非阵列 key_array
字段的文档,
{
"_id": ObjectId(...)
"key_array": 5,
"another_array": ["f"]
}
而我也想拥有一个文档
{
"_id": ObjectId(...)
"key_array": [5],
"another_array": ["f"]
}
,我也不能使用 {“ key_array”:[5]}
样式查询,因为它与现有数组与长度> 1。
那么,是否有机会在更新上保存此类行为,并在插入列表上接收正确的文档结构?
任何帮助将不胜感激
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这应该有帮助。
This should help.
https://www.mongodb.com/docs/manual/reference/operator/update/setOnInsert/
怎么样。
https://mongoplayground.net/p/4ydhkuzr2i6
how about this one.
https://mongoplayground.net/p/4YdhKuzr2I6
好的,最后,我已经通过两个连续的更新解决了这个问题,该问题是问题中指定的第一个更新 - 具有非阵列查询字段的UPSERTS,第二个将字段转换为数组(如果属于其他类型)。
但是我仍在寻找一种更优雅的方法来做这种事情。
Ok, finally I had solved this issue with two consecutive updates, the first as specified in the question - upserts with non-array query field, and the second which converts the field to an array if it belongs to another type.
But I'm still looking for a more elegant way to do such a thing.