我的MongoDB中有一个mongo集合workspaces
,其中包含如下记录:
{
"_id" : ObjectId("58bdc4a13504f5ed743ad025"),
"name" : "My workspace",
"user_id" : ObjectId("58b6cf53988a874af070fd3b"),
"uploads" : [
{
"original" : "DE-20__450_GG_5002_N23_994__0136.tif"
},
{
"original" : "DE-20__450_GG_5002_N23_994__0134.png"
},
{
"original" : "DE-20__450_GG_5002_N23_994__0136.png"
},
{
"original" : "DE-20__450_GG_5002_N23_994__0134.tif"
}
]
}
现在我的目标是,我希望在数组uploads
的记录中附加一些内容,其匹配条件为original
字段值。例如,我想以下列方式将"pseg" : "DE-20__450_GG_5002_N23_994__0136.pseg.tif"
附加到{"original" : "DE-20__450_GG_5002_N23_994__0136.tif"}
集合:
{
"_id" : ObjectId("58bdc4a13504f5ed743ad025"),
"name" : "Objective",
"user_id" : ObjectId("58b6cf53988a874af070fd3b"),
"uploads" : [
{
"original" : "DE-20__450_GG_5002_N23_994__0136.tif",
"pseg" : "DE-20__450_GG_5002_N23_994__0136.pseg.tif"
},
{
"original" : "DE-20__450_GG_5002_N23_994__0134.png"
},
{
"original" : "DE-20__450_GG_5002_N23_994__0136.png"
},
{
"original" : "DE-20__450_GG_5002_N23_994__0134.tif"
}
]
}
我尝试使用$elemMatch
然后以下列方式添加了$addToSet
:
db.getCollection('workspaces').update({"_id": ObjectId("58bdc4a13504f5ed743ad025"),"uploads": {$elemMatch: {"original": "DE-20__450_GG_5002_N23_994__0136.tif"}}},{$addToSet:{"uploads.$": {"pseg" : "DE-20__450_GG_5002_N23_994__0136.pseg.tif"}}})
但是它给了我以下错误:
Cannot apply $addToSet to a non-array field. Field named '0' has a non-array type object in the document _id: ObjectId('58bdc4a13504f5ed743ad025')
我认为我的查询错误,任何人都可以告诉我什么是错的,我该如何解决呢?
抱歉我的英语不好:)希望你明白我说的话。
答案 0 :(得分:1)
这是正确的语法。您必须使用$set
和postional
运算符来访问该元素。
db.getCollection('workspaces').update(
{"_id": ObjectId("58bdc4a13504f5ed743ad025"),"uploads": {$elemMatch: {"original": "DE-20__450_GG_5002_N23_994__0136.tif"}}},
{$set:{"uploads.$.pseg" : "DE-20__450_GG_5002_N23_994__0136.pseg.tif"}})
此处提供更多信息https://docs.mongodb.com/manual/reference/operator/update/positional/#update-documents-in-an-array
您可以简化查询条件。对于单个查询条件,您不需要使用$elemMatch
运算符。您可以使用点表示法。
db.getCollection('workspaces').update(
{"_id": ObjectId("58bdc4a13504f5ed743ad025"),"uploads.original": "DE-20__450_GG_5002_N23_994__0136.tif"},
{$set:{"uploads.$.pseg" : "DE-20__450_GG_5002_N23_994__0136.pseg.tif"}})
此处提供更多信息 https://docs.mongodb.com/manual/reference/operator/query/elemMatch/#single-query-condition