MongoDB is a document database, and each document (DOC) represents a record of the data. Instead of the relational DB row can only use simple data types, doc can use complex data types: inline doc, arrays. An array of MongoDB is a collection of elements that use brackets [] to represent an array, for example: the element of [T5] is an integer value, [{name: "}, {name:" T7 "}],[{name:" T5 ", age:21}, {name:" T7 ", age : 22}] The element is doc.
Create a sample collection, using the Db.collection.insert () function and array parameters, to insert 3 doc into the collection at once.
User1={name: ' T1 ', Age:}user2={name: ' T2 ', Age:}user3 = {name: "T3", Age:}db.users. Insert ([user1,user2,user3])
One, using dot notation (dot notation) to access array elements
MongoDB uses dot to access an array of elements, or an inline doc field.
MongoDB uses the dot notation to access the elements of a array and to access the fields of a embedded document.
Users={name: "T1", Age:+, address: {phone:123, email: "XXX@163 . com "},followers:[{name:" A "},{name:" B "},{name:" C "}]}
The Address field is an inline document that finds the phone is 123 doc
Db.users.find ({"Addr.phone":123})
The followers field is an array, and the doc that name= "B" exists in the query followers
Db.users.find ({"Followers.name": "B"})
Second, modify the value of the field
In MongoDB, the modification operation mainly uses two modifiers: $set and $inc, the two modifiers have the Upsert feature: if there is a corresponding field in the doc, then modify the value of the field, and if there is no corresponding field in Doc, create a new field in Doc. $inc used for integer fields, to increase or decrease the value of a field,$set for any data type, to replace the value of a field.
1, using the $set modifier, increase the followers array, using empty filter:{}, to update all the doc in the collection
Db.users.updateMany ({},{$set: { followers:[ {name:' T5 '},{name: ' T7 '] }})
2. Use the $inc modifier to increase the value of the age field by 1 for each Doc's age field
Db.users.updateMany ({},{$inc: {age:1}})
3, the difference between $set and $inc is that the $set replaces the value of the existing field, and $inc increases or decreases the specified value based on the existing field value
example, using $set to modify the value of age, the age field for each doc is 1 after the update is finished
Db.users.updateMany ({},{$set: {age:1}})
Third, modify the array field
If you want to add or remove an element to an array, $set and $inc do not meet this requirement well, MongoDB has a dedicated array Operator that modifies the array field.
1, use $push to add an array to the doc, or insert a new element
$push: If the corresponding array field exists in Doc, an element is inserted at the end of the array, and if the corresponding array field does not exist in Doc, an array field is created to the doc and initialized.
Example, the first call to $push, because the comments field does not exist in doc, MongoDB creates a new comments array field in Doc and initializes the array
Db.users.updateMany ({},{$push: {comments:{msg:"C1"}}})
Example, later calls $push again, appending an element to the end of an existing array field
Db.users.updateMany ({},{$push: {comments:{msg:"C2"}}})
2, inserting multiple elements into the array field
$push modifier can insert only one element at the end of an array field at a time, with the $each modifier, to insert multiple elements into an array field at a time
Db.users.updateMany ({},{$push: { comments:{$each:[ {msg:' C3 '}, {msg: ' C4 '] } }})
3, start inserting elements from a specific position in the array field
You can use the $push modifier to insert elements into the end of an array field, with the $position modifier, to specify where the element is to be inserted, $position must be used in conjunction with $each. The subscript for the array starts at 0.
Db.users.updateMany ({},{$push: {comments: { $each: [{msg:' c5 '}, {msg: ' C6 '}], $ Position:2 }} )
If you do not use the $position modifier, the $push writes the element to the end of the array each time, using the $position modifier to specify the start position of the $push insertion element.
$position : The $position modifier Specifies the location in the which the $push Operat or insert elements. Without the $position modifier, the $push operator inserts elements to the end of the array.
4, limit the number of elements in the array
When $push elements, use $slice=maxnum to limit the maximum number of array elements. As long as the maximum number is not reached, a new element is inserted into the array until the maximum value is reached. $slice must be used in conjunction with $each, if the number of elements in the array field has reached the maximum, depending on the maxnum value, there will be different behavior:
- If maxnum=0, indicates that the array is emptied;
- If Maxnum is a positive integer, the array retains only the preceding maxnum elements;
- If Maxnum is a negative integer, the array retains only the maxnum elements that follow it;
example, preserving the last 5 elements of each comments
Db.users.updateMany ({},{$push: { comments: {
$each: [{msg:' C7 '}, {msg: ' C8 '}, {msg: ' C9 '}], $slice:-5 } }})
5, sort elements of an array field
Before restricting the number of elements in an array field, the elements are sorted by using the $sort operator, which is an ordered array of elements. Use the $slice after the $sort operation: the Maxnum modifier, because the array elements are ordered, can preserve only a specific number of elements before or after the sequence.
Db.users.updateMany ({},{$push: {comments: { $each: [{msg:' C7 '}, {msg: ' C8 '}, {msg: ' C9 ' }], $sort: {msg:1}, $slice:-5 }} )
If the array is [$sort:1] This type, then it is arranged in ascending and descending order; $sort:-1, install 3,2,1 in descending order.
6, using $addtoset to insert a non-repeating element into an array
By inserting elements through $push, it is possible to insert duplicate elements, MongoDB allows elements in the array to repeat, and if an array cannot insert duplicate values, you can use the $addtoset modifier, $addToSet when inserting an element into an array, first check whether the element already exists in the array, If it does not exist, then $addtoset inserts the element into the array, and if so, $addtoset does not insert any elements. $addToSet will only guarantee that duplicate elements will not be inserted and should not affect duplicate elements that already exist in the array.
$addToSet to insert multiple elements into the array at once.
$addToSet Only ensures that there is no duplicate items added to the set and does not affect existing D Uplicate elements. $addToSet does not guarantee a particular ordering of elements in the modified set.
Example, insert three messge into the comments array
Db.users.updateMany ({},{$addToSet: {comments:[{msg:"C7"}, {msg: "C8"}, {msg: "C9"}]})
7. Use $pop to remove elements from the head or tail of an array
Consider the array as a queue, the subscript 0 element is at the end of the queue, when the element is deleted with $pop, {$pop: {array_name:n}} means that n elements are removed from the ends of the array, {$pop: {array_name:-n}} represents the deletion of n elements from the head of the array.
Db.users.updateMany (
{},
{$pop: {comments:1}}
)
8, delete array elements according to Queyr filter
Db.users.updateMany (
{},
{$pull: {comments:{msg: ' C6 '}}}
)
9, modify the element according to the subscript of the array, the array subscript is starting from 0
For the JS array arr, contains two elements, modifies the like field of the first element, and sets its value to 2.
var arr=[{name: "T1", Like:1},{name: "T2", Like:2}]arr[ 0]. like= 2 Print (Tojoson (arr))
In MongoDB, if you want to modify an array in doc, you can use dot notation to modify the elements in a specific position in the Arrary.index.field array.
Db.users.updateMany (
{},
{$inc: {"comments. 0. likes":1}}
)
If you do not know the subscript of an array element, MongoDB provides a placeholder of $, which is used to match the first element of the array to update it. The placeholder $ represents the first matching element in the format: Arrary.$.field
$: Acts as a placeholder to update the first element, that matches, the query condition in an update.
Db.users.update (
{},
{$inc: {"comments. $. Likes ": 1}}
)
10, Element match $elemMatch
$elemMatch is the field of the array element that is filtered, and if the field of the element satisfies the query criteria, the doc that contains the element is returned.
The format is: {arrar_name:{$elemMatch: {field_query_filter,,,,}}}
The $elemMatch operator matches documents that contain a array field with at least one element that matches all The specified query criteria.
Db.users.find ({comments:{$elemMatch: {like:1}})
11, Comparison of array elements
If you have the following three doc, there is one grades array in each doc:
{"_id": 1, "grades": [+,----- ]} {"_id": 2, "grades": [100, A. ]} {"_id": 3, "grades": [85,, ]}
For example 1, for query filter:{$gt: {grades:85}, $lt: {grades:100}}, analyze whether these 3 arrays meet:
- 1th array: element 90 satisfies greater than 85, all elements are less than 100
- 2nd array: All elements satisfy a condition
- 3rd array: element 90,100 satisfies conditions greater than 85, element 85,90 satisfies conditions less than 100
Therefore, as long as any one element in the array satisfies the Qeury filter, even if Qeury filter is satisfied, the 3 arrays satisfy the query filter.
Example 2,query filter:{grades:90}
The query filter is satisfied as long as the value of one element in the array is 90, so the 3 arrays satisfy the condition.
Reference doc:
Array Update Operators
Documents
Query and Projection Operators
Querying and updating of MongoDB array fields