如何将新项目推送到对象内的数组

时间:2015-06-24 18:54:24

标签: javascript json node.js mongodb

我的JSON目前看起来像这样:

{
    "_id" : 393,
    "item" : 34,
    "comments" : [
        {
            "name" : "kevin",
            "messages" : [
                "item",
                "item"
            ]
        },
        {
            "name" : "ryan",
            "messages" : [
                "item",
                "item"
            ]
        }
    ]
}

如何将新项目推送到comments数组中第一项或第二项的messages数组中?

db.newcon.update({_id: 393}, { $push: { comments['kevin']: {messages: 39 }   }  })

2 个答案:

答案 0 :(得分:4)

使用$elemMatch$运算符,您可以在下面的查询中更新您的文档:

db.collectionName.update({"_id":393,"comments":{"$elemMatch":{"name":"kevin"}}},
                         {"$push":{"comments.$.messages":39}})

答案 1 :(得分:1)

这样的事情会起作用:

hasRole([role]) Returns true if the current principal has the specified role.
hasAnyRole([role1,role2])   Returns true if the current principal has any of the supplied roles (given as a comma-separated list of strings)
principal   Allows direct access to the principal object representing the current user
authentication  Allows direct access to the current Authentication object obtained from the SecurityContext
permitAll   Always evaluates to true
denyAll Always evaluates to false
isAnonymous()   Returns true if the current principal is an anonymous user
isRememberMe()  Returns true if the current principal is a remember-me user
isAuthenticated()   Returns true if the user is not anonymous
isFullyAuthenticated()  Returns true if the user is not an anonymous or a remember-me user