Mongodb DBObject supports saving multi-dimensional arrays. When adding elements, use the "$ push" operator and "$ pull" When deleting elements ".
However, the problem arises when updating. mongodb first supports "$" to locate an element in the array, for example:
View plain
- > T. find ()
- {"_ Id": ObjectId ("4b97e62bf1d8c7152c9ccb74"), "title": "ABC ",
- "Comments": [{"by": "Joe", "votes": 3 },{ "by": "Jane", "votes": 7}]}
- > T. Update ({'comments. by': 'job'}, {$ Inc: {'comments. $. Votes ': 1 }}, false, true)
- > T. Find ()
- {"_ Id": objectid ("4b97e62bf1d8c7152c9ccb74"), "title": "ABC ",
- "Comments": [{"by": "Joe", "votes": 4 },{ "by": "Jane", "votes": 7}]}
However, the "$" operator only supports positioning one-dimensional arrays. When updating multi-dimensional arrays, an error message is returned, for example, the following data structure:
View plain
- {
- "_ Id": objectid ("4b97e62bf1d8c7152c9ccb74 "),
- "Comments": [
- {
- "By": "Joe ",
- "Votes": 3,
- "Replies ":[
- {"By": "jane ",
- "Votes": 2
- }]
- }]
- }
What should I do if I want to increase the number of votes in {"by": "jane"} "replies" by 1 (an error will be returned when I use "$" mongodb )?
Mongodb uses a multi-dimensional array to locate an element, so our method is:
First find ({"comments. replies. by ":" jane "}) to obtain the entire object, calculate the array subscript of the corresponding reply, and then use update ({" comments.0.replies. 0.by": "jane" },{ "$ inc", {"comments.0.replies. 0. votes ": 1}), so there is no synchronization problem.
Ps: in fact, the better way is to provide this subscript by the user client program, that is, the mongodb client does not need to obtain this multi-dimensional array from the server and then calculate the subscript, which is too slow. If the multi-dimensional array has been presented to the user, the subscripts can be provided by the client program, which is highly efficient.