英文:
Any way to insert fields only if they don't already exist in MongoDB?
问题
我尝试了一些我找到的解决方案,但我不明白这应该如何工作(我是Mongo的新手)。我有一个看起来像这样的文档:
{
"_id": {
"$oid": "63ef95daf324e5a26354eb61"
},
"idCarga": "6182944",
"12121212121212": {
"info1": "hello",
"info2": "goodbye"
},
"13131313131313": {
"info1": "hello",
"info2": "goodbye"
}
}
我的目标是:
- 如果我尝试使用新的产品ID字段(如15151515151515)更新文档,它将作为新字段插入。
- 如果我尝试使用已经存在的产品ID(如13131313131313)更新文档,什么都不会发生(不会插入或更新任何内容)。
我使用$exists
运算符与upsert
选项得到了一些结果。但我必须插入如此多的产品ID,这似乎是一个不可行的选项。是否有办法只使用一个文档来实现这一目标?还是我必须将其拆分为两个集合?先感谢您。
英文:
I've tried some solutions i've found but im not getting how this is supposed to work (im new to mongo). i have a document that looks like this:
{
"_id": {
"$oid": "63ef95daf324e5a26354eb61"
},
"idCarga": "6182944",
"12121212121212": {
"info1": "hello",
"info2": "goodbye"
},
"13131313131313": {
"info1": "hello",
"info2": "goodbye"
}
}
My goal is to:
- If i try to update the document with a new product ID field (like 15151515151515), it gets inserted as a new field.
- If i try to update the document with an already existing prod ID (like 13131313131313), nothing happens (dont insert or update anything).
I got some results with the $exists
operator paired with upsert
option. But i have to insert so many product IDs it seems like an unviable option. Is there any way to do this with only one document per "idCarga"? Or do i have to separate this into 2 collections? Thanks in advance.
答案1
得分: 0
以下是代码部分的中文翻译:
db.collection.update({
<您的条件>
},[
{
$set: {
"<您的ID>": {
"$ifNull": [
"$<您的ID>",
{
<您的新子文档>
}
]
}
}
}
])
英文:
Simply do a $set
with $ifNull
db.collection.update({
<your criteria>
},[
{
$set: {
"<your id>": {
"$ifNull": [
"$<your id>",
{
<your new sub doc>
}
]
}
}
}
])
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论