Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.4k views
in Technique[技术] by (71.8m points)

spring mongo - How to update particular array element in MongoDB

I am newbie in MongoDB. I have stored data inside mongoDB in below format

"_id" : ObjectId("51d5725c7be2c20819ac8a22"),
"chrom" : "chr22",
"pos" : 17060409,
"information" : [

        {
                "name" : "Category",
                "value" : "3"
        },
        {
                "name" : "INDEL",
                "value" : "INDEL"
        },
        {
                "name" : "DP",
                "value" : "31"
        },
        {
                "name" : "FORMAT",
                "value" : "GT:PL:GQ"
        },

        {
                "name" : "PV4",
                "value" : "1,0.21,0.00096,1"
        }
],
"sampleID" : "Job1373964150558382243283"

I want to update the value to 11 which has the name as Category. I have tried below query:

db.VariantEntries.update({$and:[ { "pos" : 117199533} , { "sampleID" : "Job1373964150558382243283"},{"information.name":"Category"}]},{$set:{'information.value':'11'}})

but Mongo replies

can't append to array using string field name [value]

How one can form a query which will update the particular value?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can use the $ positional operator to identify the first array element to match the query in the update like this:

db.VariantEntries.update({
    "pos": 17060409,
    "sampleID": "Job1373964150558382243283", 
    "information.name":"Category"
},{
    $set:{'information.$.value':'11'}
})

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...