我在集合中有一个文件如下:
db.persons.insert ( {
name: {first: 'Nancy', last: 'Karin'},
gender: 'F',
yearOfBirth: 1992,
livesIn: 'Montreal',
countriesVisited: ['Canada', 'United States of America'],
languages: [
{name: 'English', proficiency: 'Fluent'},
{name: 'French', proficiency: 'Fluent'},
{name: 'German', proficiency: 'Intermediate'},
{name: 'Greek', proficiency: 'Intermediate'},
{name: 'Latin', proficiency: 'Intermediate'},
{name: 'Sanskrit', proficiency: 'Beginner'} ]
} )
以下命令发出错误:
db.persons.update (
{'name.first': 'Nancy', 'name.last': 'Karin', 'languages.name': 'German'},
{$set: {'languages.?.name': 'Italian'} }
)
我得到的错误信息是:
can't append to array using string field name: ?
我看不出自己犯了什么错误。上面的命令似乎符合MongoDB 2.4.0文档,第185页,“更新元素而不指定其位置”。
感谢您的帮助。
Pradyumn
答案 0 :(得分:1)
根据docs将?
替换为$
。
答案 1 :(得分:1)
db.persons.update (
{'name.first': 'Nancy', 'name.last': 'Karin', 'languages.name': 'German'},
{$set: {'languages.$.name': 'Italian'} }
如果我们不知道数组的索引,我们必须将数据用于修改现有数据..那么我们需要使用$代表索引号..我猜它现在清楚了
答案 2 :(得分:0)
{
"_id" : ObjectId("583d79f8f6b2a2937a9da48a"),
"createdAt" : ISODate("2016-11-29T12:52:08.089Z"),
"updatedAt" : ISODate("2016-11-29T12:52:08.089Z"),
"deletedAt" : null,
"deleted" : false,
"user_id" : ObjectId("57eb939b8a1e7c6e2ea3ab21"),
"event_id" : ObjectId("57eb939b8a1e7c6e2ea3ab22"),
"order_id" : "WQArcsdcg cgf",
"amount" : 200,
"status" : "ordered",
"attachment" : [
"WQArcsdcg cgf/ACL REPORT.xls",
"WQArcsdcg cgf/woohoo.jpg"
],
"Date" : ISODate("2016-11-30T07:40:36.482Z"),
"__v" : 0
domain.GiftCard.update(
{
event_id:id,
'attachment.0':"WQArcsdcg cgf/ACL REPORT.xls",
},{
$set:{'attachment.$': "Tested By Shashwat"}
}
,function(err, res)
{
callback(null , res)
})
结果将是
{
"_id" : ObjectId("583d79f8f6b2a2937a9da48a"),
"createdAt" : ISODate("2016-11-29T12:52:08.089Z"),
"updatedAt" : ISODate("2016-11-29T12:52:08.089Z"),
"deletedAt" : null,
"deleted" : false,
"user_id" : ObjectId("57eb939b8a1e7c6e2ea3ab21"),
"event_id" : ObjectId("57eb939b8a1e7c6e2ea3ab22"),
"order_id" : "WQArcsdcg cgf",
"amount" : 200,
"status" : "ordered",
"attachment" : [
"Tested By Shashwat",
"WQArcsdcg cgf/woohoo.jpg"
],
"Date" : ISODate("2016-11-30T07:40:36.482Z"),
"__v" : 0
}