Hướng dẫn can we store array of objects in mongodb? - chúng ta có thể lưu trữ mảng các đối tượng trong mongodb không?

Tôi nhận được đối tượng Array từ phía trước và muốn lưu nó trong bộ sưu tập bằng NodeJS, MongoDB.

Đối tượng của tôi là:

routerData={"User-Name":
    {"type":"string","value":["\u0000\u0000\u0000\u0000"]},
"NAS-IP-Address":
    {"type":"ipaddr","value":["10.1.0.1"]}
},

Lược đồ bộ sưu tập của tôi là:

var model = new Schema({
routerData:{
    "User-Name": {
        "type": String,
        "value": []
    },
    "NAS-IP-Address": {
        "type": String,
        "value": []
    },

},
});

Tôi đang cố gắng với mã này:

var obj = new objModel(req.body);
obj.routerData = req.body.routerData;
obj.save(function (err, result) {

});

Tôi nhận được lỗi này:

"message": "Cast to Object failed for value \"{\"User-Name\":{\"type\":\"string\",\

Xuất bản ngày 25 tháng 5 năm 2020 Cập nhật ngày 02 tháng 6 năm 2020

1. Giới thiệu

Trong cơ sở dữ liệu MongoDB, dữ liệu được lưu trữ trong các bộ sưu tập và một bộ sưu tập có tài liệu. Một tài liệu có các trường và giá trị, như trong JSON. Các loại trường bao gồm các loại vô hướng (

var model = new Schema({
routerData:{
    "User-Name": {
        "type": String,
        "value": []
    },
    "NAS-IP-Address": {
        "type": String,
        "value": []
    },

},
});
7,
var model = new Schema({
routerData:{
    "User-Name": {
        "type": String,
        "value": []
    },
    "NAS-IP-Address": {
        "type": String,
        "value": []
    },

},
});
8,
var model = new Schema({
routerData:{
    "User-Name": {
        "type": String,
        "value": []
    },
    "NAS-IP-Address": {
        "type": String,
        "value": []
    },

},
});
9, v.v.) và các loại tổng hợp (
var obj = new objModel(req.body);
obj.routerData = req.body.routerData;
obj.save(function (err, result) {

});
0 và
var obj = new objModel(req.body);
obj.routerData = req.body.routerData;
obj.save(function (err, result) {

});
1). Trong bài viết này, chúng tôi sẽ xem xét một ví dụ về việc sử dụng loại trường Array.collections and a collection has documents. A document has fields and values, like in a JSON. The field types include scalar types (
var model = new Schema({
routerData:{
    "User-Name": {
        "type": String,
        "value": []
    },
    "NAS-IP-Address": {
        "type": String,
        "value": []
    },

},
});
7,
var model = new Schema({
routerData:{
    "User-Name": {
        "type": String,
        "value": []
    },
    "NAS-IP-Address": {
        "type": String,
        "value": []
    },

},
});
8,
var model = new Schema({
routerData:{
    "User-Name": {
        "type": String,
        "value": []
    },
    "NAS-IP-Address": {
        "type": String,
        "value": []
    },

},
});
9, etc.) and composite types (
var obj = new objModel(req.body);
obj.routerData = req.body.routerData;
obj.save(function (err, result) {

});
0 and
var obj = new objModel(req.body);
obj.routerData = req.body.routerData;
obj.save(function (err, result) {

});
1). In this article we will look at an example of using the array field type.

Ví dụ là một ứng dụng nơi người dùng tạo bài đăng trên blog và viết nhận xét cho các bài đăng. Mối quan hệ giữa các bài viết và bình luận là một-nhiều; tức là, một bài đăng có thể có nhiều ý kiến. Chúng tôi sẽ xem xét một bộ sưu tập các bài đăng trên blog với ý kiến ​​của họ. Đó là một tài liệu bài cũng sẽ lưu trữ các ý kiến ​​liên quan. Trong mô hình tài liệu của MongoDB, dữ liệu mối quan hệ 1: N có thể được lưu trữ trong một bộ sưu tập; Đây là một hình thức dữ liệu không chuẩn hóa. Các dữ liệu liên quan được lưu trữ cùng nhau và có thể được truy cập (và cập nhật) cùng nhau. Các ý kiến ​​được lưu trữ dưới dạng một mảng; Một mảng các đối tượng bình luận.

Một tài liệu mẫu của các bài đăng trên blog với nhận xét:

{
        "_id" : ObjectId("5ec55af811ac5e2e2aafb2b9"),
        "name" : "Working with Arrays",
        "user" : "Database Rebel",
        "desc" : "Maintaining an array of objects in a document",
        "content" : "some content ...",
        "created" : ISODate("2020-05-20T16:28:55.468Z"),
        "updated" : ISODate("2020-05-20T16:28:55.468Z"),
        "tags" : [ "mongodb", "arrays" ],
        "comments" : [
                {
                        "user" : "DB Learner",
                        "content" : "Nice post.",
                        "updated" : ISODate("2020-05-20T16:35:57.461Z")
                }
        ]
}

Trong một ứng dụng, một bài đăng trên blog được tạo, nhận xét được thêm vào, truy vấn, sửa đổi hoặc bị xóa bởi người dùng. Trong ví dụ, chúng tôi sẽ viết mã để tạo một tài liệu bài đăng trên blog và thực hiện một số hoạt động CRUD với các bình luận cho bài đăng.

2. Tạo và truy vấn một tài liệu

Hãy tạo một tài liệu bài đăng trên blog. Chúng tôi sẽ sử dụng cơ sở dữ liệu có tên là

var obj = new objModel(req.body);
obj.routerData = req.body.routerData;
obj.save(function (err, result) {

});
2 và một bộ sưu tập được gọi là
var obj = new objModel(req.body);
obj.routerData = req.body.routerData;
obj.save(function (err, result) {

});
3. Mã được viết bằng
var obj = new objModel(req.body);
obj.routerData = req.body.routerData;
obj.save(function (err, result) {

});
4Shell (giao diện JavaScript tương tác với MongoDB). Mongo Shell được bắt đầu từ dòng lệnh và được kết nối với máy chủ MongoDB. Từ vỏ:

use blogs

NEW_POST =
  { 
    name: "Working with Arrays",
    user: "Database Rebel",
    desc: "Maintaining an array of objects in a document",
    content: "some content...",
    created: ISODate(),
    updated: ISODate(),
    tags: [ "mongodb", "arrays" ]
}

db.posts.insertOne(NEW_POST)

Trả về kết quả

var obj = new objModel(req.body);
obj.routerData = req.body.routerData;
obj.save(function (err, result) {

});
5 chỉ ra rằng một tài liệu mới được tạo. Đây là một sự thừa nhận phổ biến khi bạn thực hiện một hoạt động viết. Khi một tài liệu được chèn vào một bộ sưu tập lần đầu tiên, bộ sưu tập sẽ được tạo (nếu nó không tồn tại). Phương thức
var obj = new objModel(req.body);
obj.routerData = req.body.routerData;
obj.save(function (err, result) {

});
6 chèn một tài liệu vào bộ sưu tập.

Bây giờ, hãy truy vấn bộ sưu tập:query the collection :

db.posts.findOne()
{
        "_id" : ObjectId("5ec55af811ac5e2e2aafb2b9"),
        "name" : "Working with Arrays",
        "user" : "Database Rebel",
        "desc" : "Maintaining an array of objects in a document",
        "content" : "some content...",
        "created" : ISODate("2020-05-20T16:28:55.468Z"),
        "updated" : ISODate("2020-05-20T16:28:55.468Z"),
        "tags" : [
                "mongodb",
                "arrays"
        ]
}

Phương pháp

var obj = new objModel(req.body);
obj.routerData = req.body.routerData;
obj.save(function (err, result) {

});
7 lấy một tài liệu phù hợp từ bộ sưu tập. Lưu ý các trường vô hướng
var obj = new objModel(req.body);
obj.routerData = req.body.routerData;
obj.save(function (err, result) {

});
8 (loại chuỗi) và
var obj = new objModel(req.body);
obj.routerData = req.body.routerData;
obj.save(function (err, result) {

});
9 (loại ngày) và trường mảng
"message": "Cast to Object failed for value \"{\"User-Name\":{\"type\":\"string\",\
0. Trong tài liệu mới được chèn không có ý kiến.

3. Thêm phần tử mảng

Hãy thêm một nhận xét cho bài đăng này, bởi người dùng "DB người học":

NEW_COMMENT = {
  user: "DB Learner",
  text: "Nice post, can I know more about the arrays in MongoDB?",
  updated: ISODate()
}

db.posts.updateOne( 
  { _id : ObjectId("5ec55af811ac5e2e2aafb2b9") },
  { $push: { comments: NEW_COMMENT } }
)

Trả lại:

"message": "Cast to Object failed for value \"{\"User-Name\":{\"type\":\"string\",\
1

Phương thức

"message": "Cast to Object failed for value \"{\"User-Name\":{\"type\":\"string\",\
2 cập nhật các trường của tài liệu dựa trên điều kiện được chỉ định.
"message": "Cast to Object failed for value \"{\"User-Name\":{\"type\":\"string\",\
3 là toán tử cập nhật mảng thêm phần tử vào một mảng. Nếu mảng không tồn tại, nó sẽ tạo một trường mảng và sau đó thêm phần tử.array update operator which adds an element to an array. If the array doesn't exist, it creates an array field and then adds the element.

Hãy truy vấn bộ sưu tập và xác nhận nhận xét mới một cách trực quan, sử dụng phương thức

var obj = new objModel(req.body);
obj.routerData = req.body.routerData;
obj.save(function (err, result) {

});
7:

{
        "_id" : ObjectId("5ec55af811ac5e2e2aafb2b9"),
        "name" : "Working with Arrays",
        ...
        "comments" : [
                {
                        "user" : "DB Learner",
                        "text" : "Nice post, can I know more about the arrays in MongoDB?",
                        "updated" : ISODate("2020-05-20T16:35:57.461Z")
                }
        ]
}

Lưu ý trường

"message": "Cast to Object failed for value \"{\"User-Name\":{\"type\":\"string\",\
5 có các đối tượng bình luận là các yếu tố. Hãy thêm một bình luận nữa bằng cách sử dụng cùng một toán tử cập nhật
"message": "Cast to Object failed for value \"{\"User-Name\":{\"type\":\"string\",\
3. Nhận xét mới này (bởi
"message": "Cast to Object failed for value \"{\"User-Name\":{\"type\":\"string\",\
7 "Cơ sở dữ liệu Rebel") được thêm vào mảng
"message": "Cast to Object failed for value \"{\"User-Name\":{\"type\":\"string\",\
5:

"comments" : [
        {
            "user" : "DB Learner",
            "text" : "Nice post, can I know more about the arrays in MongoDB?",
            "updated" : ISODate("2020-05-20T16:35:57.461Z")
        },
        {
            "user" : "Database Rebel",
            "text" : "Thank you, please look for updates",
            "updated" : ISODate("2020-05-20T16:48:25.506Z")
        }
]

4. Cập nhật phần tử mảng

Hãy cập nhật nhận xét được đăng bởi "Cơ sở dữ liệu Rebel" với trường

"message": "Cast to Object failed for value \"{\"User-Name\":{\"type\":\"string\",\
9 đã sửa đổi:
{
        "_id" : ObjectId("5ec55af811ac5e2e2aafb2b9"),
        "name" : "Working with Arrays",
        "user" : "Database Rebel",
        "desc" : "Maintaining an array of objects in a document",
        "content" : "some content ...",
        "created" : ISODate("2020-05-20T16:28:55.468Z"),
        "updated" : ISODate("2020-05-20T16:28:55.468Z"),
        "tags" : [ "mongodb", "arrays" ],
        "comments" : [
                {
                        "user" : "DB Learner",
                        "content" : "Nice post.",
                        "updated" : ISODate("2020-05-20T16:35:57.461Z")
                }
        ]
}
0.
{
        "_id" : ObjectId("5ec55af811ac5e2e2aafb2b9"),
        "name" : "Working with Arrays",
        "user" : "Database Rebel",
        "desc" : "Maintaining an array of objects in a document",
        "content" : "some content ...",
        "created" : ISODate("2020-05-20T16:28:55.468Z"),
        "updated" : ISODate("2020-05-20T16:28:55.468Z"),
        "tags" : [ "mongodb", "arrays" ],
        "comments" : [
                {
                        "user" : "DB Learner",
                        "content" : "Nice post.",
                        "updated" : ISODate("2020-05-20T16:35:57.461Z")
                }
        ]
}
0.

var model = new Schema({
routerData:{
    "User-Name": {
        "type": String,
        "value": []
    },
    "NAS-IP-Address": {
        "type": String,
        "value": []
    },

},
});
0

Toán tử cập nhật

{
        "_id" : ObjectId("5ec55af811ac5e2e2aafb2b9"),
        "name" : "Working with Arrays",
        "user" : "Database Rebel",
        "desc" : "Maintaining an array of objects in a document",
        "content" : "some content ...",
        "created" : ISODate("2020-05-20T16:28:55.468Z"),
        "updated" : ISODate("2020-05-20T16:28:55.468Z"),
        "tags" : [ "mongodb", "arrays" ],
        "comments" : [
                {
                        "user" : "DB Learner",
                        "content" : "Nice post.",
                        "updated" : ISODate("2020-05-20T16:35:57.461Z")
                }
        ]
}
1 được sử dụng để thay đổi giá trị của trường. Toán tử $ định vị xác định một phần tử trong một mảng để cập nhật mà không chỉ định rõ ràng vị trí của phần tử trong mảng. Phần tử khớp đầu tiên được cập nhật. Đối tượng nhận xét được cập nhật:update operator is used to change a field's value. The positional $ operator identifies an element in an array to update without explicitly specifying the position of the element in the array. The first matching element is updated. The updated comment object:

var model = new Schema({
routerData:{
    "User-Name": {
        "type": String,
        "value": []
    },
    "NAS-IP-Address": {
        "type": String,
        "value": []
    },

},
});
1

5. Xóa phần tử mảng

Người dùng đã thay đổi suy nghĩ của mình và muốn xóa bình luận, và sau đó thêm một bình luận mới.

var model = new Schema({
routerData:{
    "User-Name": {
        "type": String,
        "value": []
    },
    "NAS-IP-Address": {
        "type": String,
        "value": []
    },

},
});
2

Toán tử cập nhật

{
        "_id" : ObjectId("5ec55af811ac5e2e2aafb2b9"),
        "name" : "Working with Arrays",
        "user" : "Database Rebel",
        "desc" : "Maintaining an array of objects in a document",
        "content" : "some content ...",
        "created" : ISODate("2020-05-20T16:28:55.468Z"),
        "updated" : ISODate("2020-05-20T16:28:55.468Z"),
        "tags" : [ "mongodb", "arrays" ],
        "comments" : [
                {
                        "user" : "DB Learner",
                        "content" : "Nice post.",
                        "updated" : ISODate("2020-05-20T16:35:57.461Z")
                }
        ]
}
2 loại bỏ các phần tử khỏi một mảng phù hợp với điều kiện được chỉ định - trong trường hợp này là
{
        "_id" : ObjectId("5ec55af811ac5e2e2aafb2b9"),
        "name" : "Working with Arrays",
        "user" : "Database Rebel",
        "desc" : "Maintaining an array of objects in a document",
        "content" : "some content ...",
        "created" : ISODate("2020-05-20T16:28:55.468Z"),
        "updated" : ISODate("2020-05-20T16:28:55.468Z"),
        "tags" : [ "mongodb", "arrays" ],
        "comments" : [
                {
                        "user" : "DB Learner",
                        "content" : "Nice post.",
                        "updated" : ISODate("2020-05-20T16:35:57.461Z")
                }
        ]
}
3.update operator removes elements from an array which match the specified condition - in this case
{
        "_id" : ObjectId("5ec55af811ac5e2e2aafb2b9"),
        "name" : "Working with Arrays",
        "user" : "Database Rebel",
        "desc" : "Maintaining an array of objects in a document",
        "content" : "some content ...",
        "created" : ISODate("2020-05-20T16:28:55.468Z"),
        "updated" : ISODate("2020-05-20T16:28:55.468Z"),
        "tags" : [ "mongodb", "arrays" ],
        "comments" : [
                {
                        "user" : "DB Learner",
                        "content" : "Nice post.",
                        "updated" : ISODate("2020-05-20T16:35:57.461Z")
                }
        ]
}
3.

Một nhận xét mới được thêm vào mảng sau khi hoạt động xóa ở trên, với văn bản sau:

{
        "_id" : ObjectId("5ec55af811ac5e2e2aafb2b9"),
        "name" : "Working with Arrays",
        "user" : "Database Rebel",
        "desc" : "Maintaining an array of objects in a document",
        "content" : "some content ...",
        "created" : ISODate("2020-05-20T16:28:55.468Z"),
        "updated" : ISODate("2020-05-20T16:28:55.468Z"),
        "tags" : [ "mongodb", "arrays" ],
        "comments" : [
                {
                        "user" : "DB Learner",
                        "content" : "Nice post.",
                        "updated" : ISODate("2020-05-20T16:35:57.461Z")
                }
        ]
}
4.

6. Thêm một trường mới vào tất cả các đối tượng trong mảng

Hãy thêm một trường mới

{
        "_id" : ObjectId("5ec55af811ac5e2e2aafb2b9"),
        "name" : "Working with Arrays",
        "user" : "Database Rebel",
        "desc" : "Maintaining an array of objects in a document",
        "content" : "some content ...",
        "created" : ISODate("2020-05-20T16:28:55.468Z"),
        "updated" : ISODate("2020-05-20T16:28:55.468Z"),
        "tags" : [ "mongodb", "arrays" ],
        "comments" : [
                {
                        "user" : "DB Learner",
                        "content" : "Nice post.",
                        "updated" : ISODate("2020-05-20T16:35:57.461Z")
                }
        ]
}
5 cho tất cả các nhận xét trong mảng.

var model = new Schema({
routerData:{
    "User-Name": {
        "type": String,
        "value": []
    },
    "NAS-IP-Address": {
        "type": String,
        "value": []
    },

},
});
3

Tất cả toán tử vị trí

{
        "_id" : ObjectId("5ec55af811ac5e2e2aafb2b9"),
        "name" : "Working with Arrays",
        "user" : "Database Rebel",
        "desc" : "Maintaining an array of objects in a document",
        "content" : "some content ...",
        "created" : ISODate("2020-05-20T16:28:55.468Z"),
        "updated" : ISODate("2020-05-20T16:28:55.468Z"),
        "tags" : [ "mongodb", "arrays" ],
        "comments" : [
                {
                        "user" : "DB Learner",
                        "content" : "Nice post.",
                        "updated" : ISODate("2020-05-20T16:35:57.461Z")
                }
        ]
}
6 chỉ định rằng toán tử cập nhật
{
        "_id" : ObjectId("5ec55af811ac5e2e2aafb2b9"),
        "name" : "Working with Arrays",
        "user" : "Database Rebel",
        "desc" : "Maintaining an array of objects in a document",
        "content" : "some content ...",
        "created" : ISODate("2020-05-20T16:28:55.468Z"),
        "updated" : ISODate("2020-05-20T16:28:55.468Z"),
        "tags" : [ "mongodb", "arrays" ],
        "comments" : [
                {
                        "user" : "DB Learner",
                        "content" : "Nice post.",
                        "updated" : ISODate("2020-05-20T16:35:57.461Z")
                }
        ]
}
1 sẽ sửa đổi tất cả các phần tử trong trường mảng được chỉ định. Sau khi cập nhật, tất cả các đối tượng bình luận đều có trường
{
        "_id" : ObjectId("5ec55af811ac5e2e2aafb2b9"),
        "name" : "Working with Arrays",
        "user" : "Database Rebel",
        "desc" : "Maintaining an array of objects in a document",
        "content" : "some content ...",
        "created" : ISODate("2020-05-20T16:28:55.468Z"),
        "updated" : ISODate("2020-05-20T16:28:55.468Z"),
        "tags" : [ "mongodb", "arrays" ],
        "comments" : [
                {
                        "user" : "DB Learner",
                        "content" : "Nice post.",
                        "updated" : ISODate("2020-05-20T16:35:57.461Z")
                }
        ]
}
5, ví dụ:all positional operator
{
        "_id" : ObjectId("5ec55af811ac5e2e2aafb2b9"),
        "name" : "Working with Arrays",
        "user" : "Database Rebel",
        "desc" : "Maintaining an array of objects in a document",
        "content" : "some content ...",
        "created" : ISODate("2020-05-20T16:28:55.468Z"),
        "updated" : ISODate("2020-05-20T16:28:55.468Z"),
        "tags" : [ "mongodb", "arrays" ],
        "comments" : [
                {
                        "user" : "DB Learner",
                        "content" : "Nice post.",
                        "updated" : ISODate("2020-05-20T16:35:57.461Z")
                }
        ]
}
6 specifies that the update operator
{
        "_id" : ObjectId("5ec55af811ac5e2e2aafb2b9"),
        "name" : "Working with Arrays",
        "user" : "Database Rebel",
        "desc" : "Maintaining an array of objects in a document",
        "content" : "some content ...",
        "created" : ISODate("2020-05-20T16:28:55.468Z"),
        "updated" : ISODate("2020-05-20T16:28:55.468Z"),
        "tags" : [ "mongodb", "arrays" ],
        "comments" : [
                {
                        "user" : "DB Learner",
                        "content" : "Nice post.",
                        "updated" : ISODate("2020-05-20T16:35:57.461Z")
                }
        ]
}
1 should modify all elements in the specified array field. After the update, all comment objects have the
{
        "_id" : ObjectId("5ec55af811ac5e2e2aafb2b9"),
        "name" : "Working with Arrays",
        "user" : "Database Rebel",
        "desc" : "Maintaining an array of objects in a document",
        "content" : "some content ...",
        "created" : ISODate("2020-05-20T16:28:55.468Z"),
        "updated" : ISODate("2020-05-20T16:28:55.468Z"),
        "tags" : [ "mongodb", "arrays" ],
        "comments" : [
                {
                        "user" : "DB Learner",
                        "content" : "Nice post.",
                        "updated" : ISODate("2020-05-20T16:35:57.461Z")
                }
        ]
}
5 field, for example:

var model = new Schema({
routerData:{
    "User-Name": {
        "type": String,
        "value": []
    },
    "NAS-IP-Address": {
        "type": String,
        "value": []
    },

},
});
4

7. Cập nhật phần tử mảng cụ thể dựa trên điều kiện

Trước tiên, hãy thêm một nhận xét mới khác bằng toán tử cập nhật

"message": "Cast to Object failed for value \"{\"User-Name\":{\"type\":\"string\",\
3:

var model = new Schema({
routerData:{
    "User-Name": {
        "type": String,
        "value": []
    },
    "NAS-IP-Address": {
        "type": String,
        "value": []
    },

},
});
5

Lưu ý trường

{
        "_id" : ObjectId("5ec55af811ac5e2e2aafb2b9"),
        "name" : "Working with Arrays",
        "user" : "Database Rebel",
        "desc" : "Maintaining an array of objects in a document",
        "content" : "some content ...",
        "created" : ISODate("2020-05-20T16:28:55.468Z"),
        "updated" : ISODate("2020-05-20T16:28:55.468Z"),
        "tags" : [ "mongodb", "arrays" ],
        "comments" : [
                {
                        "user" : "DB Learner",
                        "content" : "Nice post.",
                        "updated" : ISODate("2020-05-20T16:35:57.461Z")
                }
        ]
}
5 bị thiếu trong tài liệu đầu vào. Chúng tôi sẽ cập nhật nhận xét cụ thể này trong mảng
"message": "Cast to Object failed for value \"{\"User-Name\":{\"type\":\"string\",\
5 với điều kiện trường
{
        "_id" : ObjectId("5ec55af811ac5e2e2aafb2b9"),
        "name" : "Working with Arrays",
        "user" : "Database Rebel",
        "desc" : "Maintaining an array of objects in a document",
        "content" : "some content ...",
        "created" : ISODate("2020-05-20T16:28:55.468Z"),
        "updated" : ISODate("2020-05-20T16:28:55.468Z"),
        "tags" : [ "mongodb", "arrays" ],
        "comments" : [
                {
                        "user" : "DB Learner",
                        "content" : "Nice post.",
                        "updated" : ISODate("2020-05-20T16:35:57.461Z")
                }
        ]
}
5 bị thiếu.

var model = new Schema({
routerData:{
    "User-Name": {
        "type": String,
        "value": []
    },
    "NAS-IP-Address": {
        "type": String,
        "value": []
    },

},
});
6

Trường

{
        "_id" : ObjectId("5ec55af811ac5e2e2aafb2b9"),
        "name" : "Working with Arrays",
        "user" : "Database Rebel",
        "desc" : "Maintaining an array of objects in a document",
        "content" : "some content ...",
        "created" : ISODate("2020-05-20T16:28:55.468Z"),
        "updated" : ISODate("2020-05-20T16:28:55.468Z"),
        "tags" : [ "mongodb", "arrays" ],
        "comments" : [
                {
                        "user" : "DB Learner",
                        "content" : "Nice post.",
                        "updated" : ISODate("2020-05-20T16:35:57.461Z")
                }
        ]
}
5 được cập nhật bằng toán tử cập nhật
use blogs

NEW_POST =
  { 
    name: "Working with Arrays",
    user: "Database Rebel",
    desc: "Maintaining an array of objects in a document",
    content: "some content...",
    created: ISODate(),
    updated: ISODate(),
    tags: [ "mongodb", "arrays" ]
}

db.posts.insertOne(NEW_POST)
4 (điều này tăng giá trị của trường hoặc nếu không tồn tại sẽ thêm trường và sau đó tăng). Toán tử vị trí được lọc
use blogs

NEW_POST =
  { 
    name: "Working with Arrays",
    user: "Database Rebel",
    desc: "Maintaining an array of objects in a document",
    content: "some content...",
    created: ISODate(),
    updated: ISODate(),
    tags: [ "mongodb", "arrays" ]
}

db.posts.insertOne(NEW_POST)
5 xác định các phần tử mảng phù hợp với các điều kiện
use blogs

NEW_POST =
  { 
    name: "Working with Arrays",
    user: "Database Rebel",
    desc: "Maintaining an array of objects in a document",
    content: "some content...",
    created: ISODate(),
    updated: ISODate(),
    tags: [ "mongodb", "arrays" ]
}

db.posts.insertOne(NEW_POST)
6 cho hoạt động cập nhật.update operator (this increments a field's value, or if not exists adds the field and then increments). The filtered positional operator
use blogs

NEW_POST =
  { 
    name: "Working with Arrays",
    user: "Database Rebel",
    desc: "Maintaining an array of objects in a document",
    content: "some content...",
    created: ISODate(),
    updated: ISODate(),
    tags: [ "mongodb", "arrays" ]
}

db.posts.insertOne(NEW_POST)
5 identifies the array elements that match the
use blogs

NEW_POST =
  { 
    name: "Working with Arrays",
    user: "Database Rebel",
    desc: "Maintaining an array of objects in a document",
    content: "some content...",
    created: ISODate(),
    updated: ISODate(),
    tags: [ "mongodb", "arrays" ]
}

db.posts.insertOne(NEW_POST)
6 conditions for an update operation.


8. Kết luận

Bài viết này cho thấy thực hiện các hoạt động CRUD cơ bản trên một loạt các đối tượng:

  • Tạo và thêm các yếu tố vào một mảng.
  • Truy vấn, cập nhật và xóa một phần tử mảng.
  • Cập nhật tất cả các phần tử mảng hoặc một yếu tố cụ thể dựa trên một điều kiện.

MongoDB cũng cho phép lập chỉ mục các phần tử mảng - trong trường hợp này, các trường của các đối tượng nhận xét của mảng

"message": "Cast to Object failed for value \"{\"User-Name\":{\"type\":\"string\",\
5. Ví dụ: nếu bạn đang truy vấn các bình luận của
use blogs

NEW_POST =
  { 
    name: "Working with Arrays",
    user: "Database Rebel",
    desc: "Maintaining an array of objects in a document",
    content: "some content...",
    created: ISODate(),
    updated: ISODate(),
    tags: [ "mongodb", "arrays" ]
}

db.posts.insertOne(NEW_POST)
8 và cần truy cập nhanh, bạn có thể tạo một chỉ mục cho trường đó. Các chỉ mục trên các trường mảng được gọi là các chỉ mục multikey. Các chỉ mục trường mảng có thể là một phần của các chỉ mục hợp chất.indexing the array elements - in this case, fields of the comment objects of the
"message": "Cast to Object failed for value \"{\"User-Name\":{\"type\":\"string\",\
5 array. For example, if you are querying on the comments by
use blogs

NEW_POST =
  { 
    name: "Working with Arrays",
    user: "Database Rebel",
    desc: "Maintaining an array of objects in a document",
    content: "some content...",
    created: ISODate(),
    updated: ISODate(),
    tags: [ "mongodb", "arrays" ]
}

db.posts.insertOne(NEW_POST)
8 and need fast access, you can create an index for that field. Indexes on array fields are called as Multikey Indexes. Array field indexes can be part of Compound Indexes.

Chúng tôi có thể thực hiện nhiều hoạt động khác trên các mảng - dự đoán, truy vấn và cập nhật - sử dụng các toán tử khác nhau cũng như đường ống tổng hợp. Ngoài ra, thực hiện các hoạt động này trên các mảng lồng nhau (mảng trong mảng). Chúng tôi sẽ thấy một số tính năng này trong một bài viết sau.operations on the arrays - projections, querying and updating - using various operators as well as the Aggregation Pipeline. Also, perform these operations on nested arrays (arrays within arrays). We will see some of these features in a later article.


8.1. Liên kết hữu ích

  • Vỏ Mongo
  • db.collection.InsertOne
  • db.collection.updateOne
  • db.collection.findOne
  • Các nhà khai thác cập nhật: $ set, $ push, $ pull, $ inc, $, $ [], $ []

Chúng ta có thể lưu trữ các đối tượng trong MongoDB không?

Các đối tượng lớn, hoặc "tệp", dễ dàng được lưu trữ trong MongoDB.Không có vấn đề gì để lưu trữ video 100MB trong cơ sở dữ liệu.. It is no problem to store 100MB videos in the database.

Làm cách nào để truy vấn một loạt các đối tượng trong MongoDB?

Để tìm kiếm mảng đối tượng trong MongoDB, bạn có thể sử dụng toán tử elemmatch $.Toán tử này cho phép chúng tôi tìm kiếm nhiều hơn một thành phần từ một đối tượng mảng.use $elemMatch operator. This operator allows us to search for more than one component from an array object.

Làm cách nào để đẩy một đối tượng mảng trong MongoDB?

Trong MongoDB, toán tử Push $ được sử dụng để nối một giá trị được chỉ định vào một mảng.Nếu trường được đề cập không có trong tài liệu để cập nhật, toán tử Push $ thêm nó dưới dạng trường mới và bao gồm giá trị được đề cập làm yếu tố của nó.Nếu trường cập nhật không phải là trường loại mảng thì hoạt động không thành công.the $push operator is used to appends a specified value to an array. If the mentioned field is absent in the document to update, the $push operator add it as a new field and includes mentioned value as its element. If the updating field is not an array type field the operation failed.

MongoDB có bảo quản đơn đặt hàng mảng không?

Yep MongoDB giữ thứ tự của mảng .. giống như động cơ javascript .... just like Javascript engines..