0

I would like to insert a document into an array within another document in Powershell.

e.g.

{
        "1" : "A",
        "2" : "B",
        "3" : [
                {
                        "a" : "AA",
                        "_id" : ObjectId("5333b74c9e99569836bca41f")
                }
        ],
        "_id" : ObjectId("5333b74c9e99569836bca41c")
}

this is my document in mongodb shell.

{
        "1" : "A",
        "2" : "B",
        "3" : [ ]
        "_id" : ObjectId("5333b74c9e99569836bca41c")
}

and this is my code in powershell:

$embededDocument = new-object Mongodb.Bson.BsonDocument
$embededDocument.Add("a", "AA")
$embededDocument.Add("B2", "2")
$embededDocument.Add("C2", "3")

$parentDocument["3"].Add($embededDocument)

this is not working as the array is empty after run the code, I tried using Add, Insert and Push with same result...

Any idea what I'm doing wrong?

thank you very much

2 Answers 2

1

Basically you are trying to do an update of the type that is shown for the $push operator, as shown in the documentation. So you need to construct the same sort of BSON document structure as shown there:

$query = [MongoDB.Driver.Builders.Query]::EQ("_id" :
    [MongoDB.Bson.BsonObjectId]::Create("5333b74c9e99569836bca41c"))

$doc = new-object MongoDB.Bson.Document
$doc.Add("a", "AA")

$inner = new-object MongoDB.Bson.Document
$inner.Add( "3", $doc )

$update = new-object MongoDB.Bson.Document
$update.Add('$push', $inner)

$collection.update($query,$update)

This comes out the be the equivalent of this:

db.collection.update(
    { _id: ObjectId("5333b74c9e99569836bca41c") },
    {
        "$push": { "3": { "a": "AA" } }
    }
)

MongoDB does not create ObjectId values automatically inside array elements in the way you have shown. If you want to create them then you need to add the fields and created ObjectId values yourself.

For any other reference, use the C# documentation which is essentially the API you are using with powershell.

Sign up to request clarification or add additional context in comments.

Comments

0

If you use the push operation or such like that,you are supposed to call the save() after that or I don't think your document would be saved. As a result, your array will always be null.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.