0

I'm having issue with adding a key value pair to an array that has the same name. Is there a way to add it according to index?

I've tried finding key in the search query which works. But updating adds it the bottom of the document

db.getCollection('siteLog').updateOne(
{
    'site':'test1',
    'items.suspiciousActivity.source': 'Account Added to Admin Group'
},
    {$set:
        {'items.suspiciousActivity.source.Account Added to Admin Group' : 'summary':'test1'}
     })

It should be added towards the bottom with another key value pair

"items" : [ 
        {
            "suspiciousActivity" : {
                "source" : "Account Added to Admin Group",
                "count" : "2",
                "summary" : "Test summary for this"
            }
        }, 
        {
            "suspiciousActivity" : {
                "source" : "Palo Alto FW - Local Account Login",
                "count" : "2",
                "summary" : "Another test summary"
            }
        }, 
        {
            "suspiciousActivity" : {
                "source" : "Suspicious Failed Logon Attempts",
                "count" : "2",
                "summary": "more summaries"
            }
        }, 
Vinh Ta
  • 117
  • 3
  • 12
  • Uhh... what exactly do you want to do? Can you clarify on where the pairs need to be added? You said "It should be added towards the bottom with another key value pair", but you also said "But updating adds it the bottom of the document". Which kind of makes me think that you don't want that and at the same time that you do? Also if you have dictionary, it's not exactly "orderly" or "sorted" in any way, because you access values through keys, so you don't need to index it. – SkyAnthrax94 Jun 05 '19 at 17:02
  • It adds it outside of the items array instead of inside of suspiciousActivity. `"items" : [ { "suspiciousActivity" : { "source" : "Account Added to Admin Group", "count" : "2",` – Vinh Ta Jun 05 '19 at 17:07

1 Answers1

1

You need to use $ to get the correct items index, like this:

db.getCollection('siteLog').updateOne({
    'site': 'test1',
    'items.suspiciousActivity.source': 'Account Added to Admin Group'
}, {
    $set: {
        'items.$.suspiciousActivity.summary': 'test1'
    }
})
Matheus Hatje
  • 987
  • 1
  • 7
  • 18