Sub document insertion problem

131 views
Skip to first unread message

shakthydoss

unread,
Aug 20, 2011, 9:27:32 AM8/20/11
to mongodb-user
Hi ... i have document like ...

{
_id: 1000

"A":[{
"A_id":1016,
"A1":[{
"A1_id":1001
},
{
"A1_id":1002
}
]
}
],
"B":[{
"B_id":1016,
"b1":[{
"b1_id":1001
},
{
"b1_id":1002
}
]
}
]
}



i tired to insert an sub document below "A1_id":1001
if i include successfully then document will look like

{
"A":[{
"A_id":1016,
"A1":[{
"A1_id":1001,
"A1_1":[{
"A1_1_content":"content"
}
]
},
{
"A1_id":1002
}
]
}
],
"B":[{
"B_id":1015,
"b1":[{
"b1_id":1001
},
{
"b1_id":1002
}
]
}
]
}



but i am not able in insert that properly and i use the following
query

> db.blog.update({"_id":1000,"A.A1.A1_id":1001},{"$push":{"A.$.A1_1_content":comm}})


any one tell me what is that right query that i have to use
thank you.


Marc

unread,
Aug 22, 2011, 7:15:26 PM8/22/11
to mongodb-user
The update method takes two parameters: a query document, which
locates the document(s) to update, and a modifier document, which
describes the changes to the documents found.

Only one query document may be input, so when matching documents
inside of arrays inside of documents inside of arrays, the location of
one of the documents must be known inside of one of the arrays.

Either of these commands will work:
(In this example, the collection name is "test".)

> db.test.update({'A.A_id':1016}, {$set:{"A.$.A1.0.A1_1":[{A1_1_content:"content"}]}})

> db.test.update({'A.A1.A1_id':1001}, {$set:{"A.0.A1.$.A1_1":[{A1_1_content:"content"}]}})

The "$" character acts as a pointer to the location in the array where
the document matching the query was found. Here is a link to the "The
$ positional operator" section of the update() section of the MongoDB
guide.

http://www.mongodb.org/display/DOCS/Updating#Updating-The%24positionaloperator

If the positions in both arrays are known, the following will also
work:
> db.test.update({'_id':1000}, {$set:{"A.0.A1.0.A1_1":[{A1_1_content:"content"}]}})

It may be beneficial, if possible, to rearrange the data such that it
does not rely on nested arrays.

Perhaps something like:

{_id: 1000,
"A":{_id:1016,
"A1":{_id:1001},
"A2":{_id:1002} },
"B":{_id:1016,
"B1":{_id:1001},
"B2":{_id:1002} } }

Fields may be added using the $set command:

db.test.update({"A.A1._id":1001},{$set:{"A.A1.content":"Content"}})

Resulting in:

{_id: 1000,
"A":{_id:1016,
"A1":{_id:1001,
"content" : "Content" },
"A2":{_id:1002} },
"B":{_id:1016,
"B1":{_id:1001},
"B2":{_id:1002} } }
Reply all
Reply to author
Forward
0 new messages