4

I have a document structure like

{
    "_id" : ObjectId("52263922f5ebf05115bf550e"),
    "Fields" : [
        {
            "Field" : "Lot No",
            "Rules" : [ ]
        },
        {
            "Field" : "RMA No",
            "Rules" : [ ]
        }
    ]
}

I have tried to update by using the following code to push into the Rules Array which will hold objects.

db.test.update({
    "Fields.Field":{$in:["Lot No"]}
}, {
    $addToSet: {
        "Fields.Field.$.Rules": {
            "item_name": "my_item_two",
            "price": 1
        }
    }
}, false, true);

But I get the following error:

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

How do I do the update?

1
  • 1
    I think you have a superfluous Field in your $addToSet-Operator. Try $addToSet: { "Fields.$.Rules": ... Commented Sep 3, 2013 at 20:50

1 Answer 1

4

You gone too deep with that wildcard $. You match for an item in the Fields array, so you get a access on that, with: Fields.$. This expression returns the first match in your Fields array, so you reach its fields by Fields.$.Field or Fields.$.Result.

Now, lets update the update:

db.test.update({
    "Fields.Field": "Lot No"
}, {
    $addToSet: {
        "Fields.$.Rules": {
            'item_name': "my_item_two",
            'price':1
        }
    }
}, false, true);

Please note that I've shortened the query as it is equal to your expression.

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

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.