如果不存在特定的键值,则给定数组的推送对象到MongoDB文档的数组
可以说,我现在像Pymongo一样在Mongo中有一个文档
{
name: "abc",
manufacturer: "xyz",
...
history: [
{"condition": "new", "price": 150, "currency": "USD", "timestamp": "aaaaaaaaaaaa"}
]
}
,我想更新与过滤器(否则插入)匹配(否则插入)的文档,如果该字典在那里(Mongo doc的历史记录阵列)中不存在,并将每个字典推在历史记录列表中 以上查询的查询
history = [
{"condition": "new", "price": 150, "currency": "USD", "timestamp": "bbbbbbbbbbbb"},
{"condition": "used", "price": 90, "currency": "USD", "timestamp": "cccccccccccc"},
]
item = {
"name": "abcd",
"manufacture": "xyz"
}
db.collection.update_one(filter, {"$set": item, "$addToSet": {"history": {"$each": history}}}, True)
问题是我想从 $ $ addtoset 的比较中排除时间戳字段(最终将是唯一的,最终导致字典被推开),这是根据我的研究不可能的。
因此,我试图避免进行两个单独的查询(以避免绩效问题,因为我的收藏包含数百万个文档)与我相当新的聚合管道,并希望得到任何帮助。 MongoDB中更新的文档应该看起来像
{
name: "abcd",
manufacturer: "xyz",
...
history: [
{"condition": "new", "price": 150, "currency": "USD", "timestamp": "aaaaaaaaaaaa"},
{"condition": "used", "price": 90, "currency": "USD", "timestamp": "cccccccccccc"}
]
}
Lets say I have a document in mongo like
{
name: "abc",
manufacturer: "xyz",
...
history: [
{"condition": "new", "price": 150, "currency": "USD", "timestamp": "aaaaaaaaaaaa"}
]
}
Now with pymongo, I want to update the document that matches the filter(otherwise insert) and push each dictionary in history list if that dictionary does not exist there(in mongo doc's history array) with the following query
history = [
{"condition": "new", "price": 150, "currency": "USD", "timestamp": "bbbbbbbbbbbb"},
{"condition": "used", "price": 90, "currency": "USD", "timestamp": "cccccccccccc"},
]
item = {
"name": "abcd",
"manufacture": "xyz"
}
db.collection.update_one(filter, {"$set": item, "$addToSet": {"history": {"$each": history}}}, True)
Problem with above query is that I want to exclude the timestamp field(as it would always be unique eventually causing the dictionary to be pushed) from comparison of $addToSet which is not possible as per my research.
So I am trying to avoid doing two separate queries(to avoid performance issues as my collection contains millions of documents) with the an aggregation pipeline to which I am fairly new and would appreciate any help.
The updated document in mongodb should look like
{
name: "abcd",
manufacturer: "xyz",
...
history: [
{"condition": "new", "price": 150, "currency": "USD", "timestamp": "aaaaaaaaaaaa"},
{"condition": "used", "price": 90, "currency": "USD", "timestamp": "cccccccccccc"}
]
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
一种选项是将Update与Pipeline一起使用,例如:
$ setDifference
从新清洁中删除现有的历史记录密钥。$ MERGE
仅使用具有所有数据的新历史记录后留下的历史记录对象。Playground示例
One option is to use update with pipeline, like this:
$setDifference
to remove existing history keys from the new clean one.$merge
only the history object that left after the removal with the new history that have all the data.Playground example