1

我在集合中有一个文档,如下所示:

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 页,“更新元素而不指定其位置”。

谢谢你的帮助。

普拉敦

4

3 回答 3

1

?根据docs替换。$_

于 2013-09-21T08:33:23.710 回答
1
db.persons.update (
    {'name.first': 'Nancy', 'name.last': 'Karin', 'languages.name': 'German'},
    {$set: {'languages.$.name': 'Italian'} }

如果我们不知道我们必须放置数据以修改现有数据的数组的索引..那么我们需要使用 $ 代表索引号..我想现在很清楚了

于 2017-04-14T09:38:06.293 回答
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

}

于 2017-04-14T10:07:06.330 回答