在mongodb中查询文档中的嵌入式数组字段

时间:2016-04-28 10:16:02

标签: mongodb

在mongodb数据库中,我在尝试查询字段时遇到问题。我的收藏用户看起来像这样:

{

"_id" : "sam",
"_password" : "t",
"data" : [
    {
        "_id" : "hp",
        "nodeList" : [{'nodeId' : 1},{'nodeId' : 2},{'nodeId' : 3}],
        "edgeList" : [{'edgeId' : 1},{'edgeId' : 2},{'edgeId' : 3}],
        "options" : {
            "edgeColor" : "blue",
            "nodeColor" : "black"
        }
    },
    {
        "_id" : "tt",
        "nodeList" : [{'nodeId' : 1},{'nodeId' : 2},{'nodeId' : 3}],
        "edgeList" : [{'edgeId' : 1},{'edgeId' : 2},{'edgeId' : 3}],
        "options" : {
            "edgeColor" : "blue",
            "nodeColor" : "black"
        }
    }
]}, 

{

"_id" : "bob",
"_password" : "w",
"data" : [
    {
        "_id" : "hello",
        "nodeList" : [{'nodeId' : 1},{'nodeId' : 2},{'nodeId' : 3}],
        "edgeList" : [{'edgeId' : 1},{'edgeId' : 2},{'edgeId' : 3}],
        "options" : {
            "edgeColor" : "blue",
            "nodeColor" : "black"
        }
    },
    {
        "_id" : "world",
        "nodeList" : [{'nodeId' : 1},{'nodeId' : 2},{'nodeId' : 3}],
        "edgeList" : [{'edgeId' : 1},{'edgeId' : 2},{'edgeId' : 3}],
        "options" : {
            "edgeColor" : "blue",
            "nodeColor" : "black"
        }
    }
]
}

我需要从中检索nodeList/edgeLis t,并在给定特定_id的选项中更改edgeColor。例如:_ id : "bob"

我尝试了一些但却无法获得输出。

db.users.find({ '_id': 'sam' , "users.data._id" : "hp"}, {})
db.users.findOneAndUpdate({"_id":"sam", "users.data._id": "hp"},{$addToSet:{"users.data.nodeList":{"nodeId":1,"nodeName":"Bellanduru", "lat":43.12, "long":33.43,"stock":3}}})

请告诉我错误。

1 个答案:

答案 0 :(得分:0)

您在选定的数据库

中使用此db.users声明您的集合名称

并选择users集合,因此无需在查询中指定

例如,此"users.data._id"替换为此"data._id"

像这样替换你的查询

db.users.find({ '_id': 'sam' , "data._id" : "hp"}, {})
db.users.findOneAndUpdate({"_id":"sam", "data._id": "hp"},{$addToSet:{"data.nodeList":{"nodeId":1,"nodeName":"Bellanduru", "lat":43.12, "long":33.43,"stock":3}}})