Hướng dẫn how manually insert data in mongodb atlas? - cách chèn thủ công dữ liệu vào tập bản đồ mongodb?

Tài liệu về nhà → MongoDB AtlasMongoDB Atlas

Trên trang này

  • Chèn và xem dữ liệu
  • Bước tiếp theo

Chèn và xem dữ liệu

Bước tiếp theo

Thời gian hoàn thành ước tính: 5 phútMongoDB Drivers. MongoDB drivers allow you to interact with your databases programmatically using a supported programming language.

Các bước trong hướng dẫn này chỉ cho bạn cách chèn dữ liệu vào cụm của bạn bằng một trong các trình điều khiển MongoDB được hỗ trợ. Trình điều khiển MongoDB cho phép bạn tương tác với cơ sở dữ liệu của mình bằng cách sử dụng ngôn ngữ lập trình được hỗ trợ.

Bước tiếp theo

Thời gian hoàn thành ước tính: 5 phút

Trên trang này

  • Chèn và xem dữ liệu
  • Bước tiếp theo

Chúng ta có thể chèn một tệp trong MongoDB không?Start with Guides

Shell MongoDB cung cấp các phương thức sau để chèn tài liệu vào một bộ sưu tập: Để chèn một tài liệu duy nhất, hãy sử dụng db.collection.insertone ()

Bạn sẽ sử dụng phương pháp nào để chèn một dữ liệu trên MongoDB?

  • Chèn () chèn một tài liệu duy nhất vào một bộ sưu tập. Ví dụ sau đây chèn một tài liệu mới vào bộ sưu tập hàng tồn kho. Nếu tài liệu không chỉ định trường _ID, MongoDB sẽ thêm trường _id có giá trị ObjectID vào tài liệu mới.

  • Tài liệu về nhà → Bắt đầu với hướng dẫn

  • Trong hướng dẫn này, bạn sẽ chèn dữ liệu vào MongoDB.

Thời gian cần thiết: 15 phút

Một chuỗi kết nối với triển khai MongoDB của bạn.

  • Tên

  • Tên chính thức

  • Thời kỳ quỹ đạo trong các năm

  • Bán kính tính bằng dặm

  • Khối lượng tính bằng kilogam

Mẹo

Nếu bạn bỏ qua trường

const doc1 = { "name": "basketball", "category": "sports", "quantity": 20, "reviews": [] };
const doc2 = { "name": "football", "category": "sports", "quantity": 30, "reviews": [] };
return itemsCollection.insertMany([doc1, doc2])
.then(result => {
console.log(`Successfully inserted ${result.insertedIds.length} items!`);
return result
})
.catch(err => console.error(`Failed to insert documents: ${err}`))
2, trình điều khiển sẽ tự động tạo giá trị
const doc1 = { "name": "basketball", "category": "sports", "quantity": 20, "reviews": [] };
const doc2 = { "name": "football", "category": "sports", "quantity": 30, "reviews": [] };
return itemsCollection.insertMany([doc1, doc2])
.then(result => {
console.log(`Successfully inserted ${result.insertedIds.length} items!`);
return result
})
.catch(err => console.error(`Failed to insert documents: ${err}`))
3 duy nhất cho trường
const doc1 = { "name": "basketball", "category": "sports", "quantity": 20, "reviews": [] };
const doc2 = { "name": "football", "category": "sports", "quantity": 30, "reviews": [] };
return itemsCollection.insertMany([doc1, doc2])
.then(result => {
console.log(`Successfully inserted ${result.insertedIds.length} items!`);
return result
})
.catch(err => console.error(`Failed to insert documents: ${err}`))
2.

Nhiều hoạt động ghi trong MongoDB trả về một đối tượng kết quả có chứa thông tin về hoạt động.

Dưới đây là mã hoàn chỉnh theo sau là đầu ra mẫu.

Ghi chú

Giá trị

const doc1 = { "name": "basketball", "category": "sports", "quantity": 20, "reviews": [] };
const doc2 = { "name": "football", "category": "sports", "quantity": 30, "reviews": [] };
return itemsCollection.insertMany([doc1, doc2])
.then(result => {
console.log(`Successfully inserted ${result.insertedIds.length} items!`);
return result
})
.catch(err => console.error(`Failed to insert documents: ${err}`))
3 của bạn sẽ khác với các giá trị được hiển thị.

Nếu bạn đã hoàn thành hướng dẫn này, bạn đã chèn dữ liệu vào MongoDB.

Trong hướng dẫn tiếp theo, bạn sẽ tìm hiểu cách cập nhật một trường trong một tài liệu.

Xem các tài nguyên sau đây để biết thêm thông tin chuyên sâu về các khái niệm được trình bày ở đây:

  • Chèn tài liệu

  • Phương pháp chèn

Tài liệu về nhà → Hướng dẫn sử dụng MongoDBMongoDB Manual


Sử dụng menu chọn ngôn ngữ của bạn ở phía trên bên phải để đặt ngôn ngữ của các ví dụ trên trang này.Select your language drop-down menu in the upper-right to set the language of the examples on this page.


Trang này cung cấp các ví dụ về các hoạt động chèn trong MongoDB.

Ghi chú

Tạo một bộ sưu tập

Nếu bộ sưu tập hiện không tồn tại, các hoạt động chèn sẽ tạo ra bộ sưu tập.

Để truy xuất tài liệu mà bạn vừa chèn, truy vấn bộ sưu tập:


Sử dụng menu chọn ngôn ngữ của bạn ở phía trên bên phải để đặt ngôn ngữ của các ví dụ trên trang này.Select your language drop-down menu in the upper-right to set the language of the examples on this page.


Nếu bộ sưu tập hiện không tồn tại, các hoạt động chèn sẽ tạo ra bộ sưu tập.

Để truy xuất tài liệu mà bạn vừa chèn, truy vấn bộ sưu tập:

Trong MongoDB, mỗi tài liệu được lưu trữ trong một bộ sưu tập đòi hỏi một trường _ID duy nhất hoạt động như một khóa chính. Nếu một tài liệu được chèn bỏ qua trường

const doc1 = { "name": "basketball", "category": "sports", "quantity": 20, "reviews": [] };
const doc2 = { "name": "football", "category": "sports", "quantity": 30, "reviews": [] };
return itemsCollection.insertMany([doc1, doc2])
.then(result => {
console.log(`Successfully inserted ${result.insertedIds.length} items!`);
return result
})
.catch(err => console.error(`Failed to insert documents: ${err}`))
2, trình điều khiển MongoDB sẽ tự động tạo một ObjectID cho trường
const doc1 = { "name": "basketball", "category": "sports", "quantity": 20, "reviews": [] };
const doc2 = { "name": "football", "category": "sports", "quantity": 30, "reviews": [] };
return itemsCollection.insertMany([doc1, doc2])
.then(result => {
console.log(`Successfully inserted ${result.insertedIds.length} items!`);
return result
})
.catch(err => console.error(`Failed to insert documents: ${err}`))
2.

Điều này cũng áp dụng cho các tài liệu được chèn thông qua các hoạt động cập nhật với UPSERT: true.

Tất cả các hoạt động viết trong MongoDB đều là nguyên tử ở cấp độ của một tài liệu. Để biết thêm thông tin về MongoDB và tính nguyên tử, hãy xem tính nguyên tử và giao dịch

DOCS Home → Dịch vụ ứng dụng AtlasAtlas App Services

Trên trang này

  • Tổng quan
  • Mô hình dữ liệu
  • Thiết lập đoạn trích
  • Chèn
  • Chèn một tài liệu duy nhất (
    const doc1 = { "name": "basketball", "category": "sports", "quantity": 20, "reviews": [] };
    const doc2 = { "name": "football", "category": "sports", "quantity": 30, "reviews": [] };
    return itemsCollection.insertMany([doc1, doc2])
    .then(result => {
    console.log(`Successfully inserted ${result.insertedIds.length} items!`);
    return result
    })
    .catch(err => console.error(`Failed to insert documents: ${err}`))
    8)
  • Chèn một hoặc nhiều tài liệu (
    const doc1 = { "name": "basketball", "category": "sports", "quantity": 20, "reviews": [] };
    const doc2 = { "name": "football", "category": "sports", "quantity": 30, "reviews": [] };
    return itemsCollection.insertMany([doc1, doc2])
    .then(result => {
    console.log(`Successfully inserted ${result.insertedIds.length} items!`);
    return result
    })
    .catch(err => console.error(`Failed to insert documents: ${err}`))
    9)
  • Cập nhật
  • Cập nhật một tài liệu duy nhất (
    const query = { "name": "lego" };
    const update = {
    "$set": {
    "name": "blocks",
    "price": 20.99,
    "category": "toys"
    }
    };
    const options = { "upsert": false };
    itemsCollection.updateOne(query, update, options)
    .then(result => {
    const { matchedCount, modifiedCount } = result;
    if(matchedCount && modifiedCount) {
    console.log(`Successfully updated the item.`)
    }
    })
    .catch(err => console.error(`Failed to update the item: ${err}`))
    0)
  • Cập nhật một hoặc nhiều tài liệu (
    const query = { "name": "lego" };
    const update = {
    "$set": {
    "name": "blocks",
    "price": 20.99,
    "category": "toys"
    }
    };
    const options = { "upsert": false };
    itemsCollection.updateOne(query, update, options)
    .then(result => {
    const { matchedCount, modifiedCount } = result;
    if(matchedCount && modifiedCount) {
    console.log(`Successfully updated the item.`)
    }
    })
    .catch(err => console.error(`Failed to update the item: ${err}`))
    1)
  • Tài liệu UPSERT
  • Các nhà khai thác cập nhật hiện trường
  • Các nhà khai thác cập nhật mảng
  • Xóa bỏ
  • Xóa một tài liệu duy nhất (
    const query = { "name": "lego" };
    const update = {
    "$set": {
    "name": "blocks",
    "price": 20.99,
    "category": "toys"
    }
    };
    const options = { "upsert": false };
    itemsCollection.updateOne(query, update, options)
    .then(result => {
    const { matchedCount, modifiedCount } = result;
    if(matchedCount && modifiedCount) {
    console.log(`Successfully updated the item.`)
    }
    })
    .catch(err => console.error(`Failed to update the item: ${err}`))
    2)
  • Xóa một hoặc nhiều tài liệu (
    const query = { "name": "lego" };
    const update = {
    "$set": {
    "name": "blocks",
    "price": 20.99,
    "category": "toys"
    }
    };
    const options = { "upsert": false };
    itemsCollection.updateOne(query, update, options)
    .then(result => {
    const { matchedCount, modifiedCount } = result;
    if(matchedCount && modifiedCount) {
    console.log(`Successfully updated the item.`)
    }
    })
    .catch(err => console.error(`Failed to update the item: ${err}`))
    3)
  • Viết số lượng lớn
  • Giao dịch

Các ví dụ trên trang này trình bày cách sử dụng API truy vấn MongoDB trong một hàm để chèn, cập nhật và xóa dữ liệu trong cụm Atlas của bạn.

Ghi chú

Các ví dụ trên trang này sử dụng một bộ sưu tập có tên

const query = { "name": "lego" };
const update = {
"$set": {
"name": "blocks",
"price": 20.99,
"category": "toys"
}
};
const options = { "upsert": false };
itemsCollection.updateOne(query, update, options)
.then(result => {
const { matchedCount, modifiedCount } = result;
if(matchedCount && modifiedCount) {
console.log(`Successfully updated the item.`)
}
})
.catch(err => console.error(`Failed to update the item: ${err}`))
4 mô hình các mặt hàng khác nhau có sẵn để mua trong một cửa hàng trực tuyến. Mỗi mặt hàng có
const query = { "name": "lego" };
const update = {
"$set": {
"name": "blocks",
"price": 20.99,
"category": "toys"
}
};
const options = { "upsert": false };
itemsCollection.updateOne(query, update, options)
.then(result => {
const { matchedCount, modifiedCount } = result;
if(matchedCount && modifiedCount) {
console.log(`Successfully updated the item.`)
}
})
.catch(err => console.error(`Failed to update the item: ${err}`))
5, hàng tồn kho
const query = { "name": "lego" };
const update = {
"$set": {
"name": "blocks",
"price": 20.99,
"category": "toys"
}
};
const options = { "upsert": false };
itemsCollection.updateOne(query, update, options)
.then(result => {
const { matchedCount, modifiedCount } = result;
if(matchedCount && modifiedCount) {
console.log(`Successfully updated the item.`)
}
})
.catch(err => console.error(`Failed to update the item: ${err}`))
6 và một loạt khách hàng
const query = { "name": "lego" };
const update = {
"$set": {
"name": "blocks",
"price": 20.99,
"category": "toys"
}
};
const options = { "upsert": false };
itemsCollection.updateOne(query, update, options)
.then(result => {
const { matchedCount, modifiedCount } = result;
if(matchedCount && modifiedCount) {
console.log(`Successfully updated the item.`)
}
})
.catch(err => console.error(`Failed to update the item: ${err}`))
7.

Lược đồ JSON cho Store.Items

{
"title": "Item",
"required": ["_id", "name", "quantity", "reviews"],
"properties": {
"_id": { "bsonType": "objectId" },
"name": { "bsonType": "string" },
"quantity": { "bsonType": "int" },
"reviews": {
"bsonType": "array",
"items": {
"bsonType": "object",
"required": ["username", "comment"],
"properties": {
"username": { "bsonType": "string" },
"comment": { "bsonType": "string" }
}
}
}
}
}

Để sử dụng đoạn mã trong một hàm, trước tiên bạn phải khởi tạo một tay cầm bộ sưu tập MongoDB:

exports = function() {
const mongodb = context.services.get("mongodb-atlas");
const itemsCollection = mongodb.db("store").collection("items");
const purchasesCollection = mongodb.db("store").collection("purchases");
// ... paste snippet here ...
}

Chèn các hoạt động lấy một hoặc nhiều tài liệu và thêm chúng vào bộ sưu tập MongoDB.

Họ trả lại các tài liệu mô tả kết quả của hoạt động.

Bạn có thể chèn một tài liệu bằng phương thức

const query = { "name": "lego" };
const update = {
"$set": {
"name": "blocks",
"price": 20.99,
"category": "toys"
}
};
const options = { "upsert": false };
itemsCollection.updateOne(query, update, options)
.then(result => {
const { matchedCount, modifiedCount } = result;
if(matchedCount && modifiedCount) {
console.log(`Successfully updated the item.`)
}
})
.catch(err => console.error(`Failed to update the item: ${err}`))
8.

Snippet chức năng sau chèn một tài liệu một mục vào bộ sưu tập

const query = { "name": "lego" };
const update = {
"$set": {
"name": "blocks",
"price": 20.99,
"category": "toys"
}
};
const options = { "upsert": false };
itemsCollection.updateOne(query, update, options)
.then(result => {
const { matchedCount, modifiedCount } = result;
if(matchedCount && modifiedCount) {
console.log(`Successfully updated the item.`)
}
})
.catch(err => console.error(`Failed to update the item: ${err}`))
9:

const newItem = {
"name": "Plastic Bricks",
"quantity": 10,
"category": "toys",
"reviews": [{ "username": "legolover", "comment": "These are awesome!" }]
};
itemsCollection.insertOne(newItem)
.then(result => console.log(`Successfully inserted item with _id: ${result.insertedId}`))
.catch(err => console.error(`Failed to insert item: ${err}`))

Bạn có thể chèn nhiều tài liệu cùng một lúc bằng phương pháp

const query = {};
const update = { "$mul": { "quantity": 10 } };
const options = { "upsert": false }
return itemsCollection.updateMany(query, update, options)
.then(result => {
const { matchedCount, modifiedCount } = result;
console.log(`Successfully matched ${matchedCount} and modified ${modifiedCount} items.`)
return result
})
.catch(err => console.error(`Failed to update items: ${err}`))
0.

Đoạn mã sau này chèn nhiều tài liệu mục vào bộ sưu tập

const query = { "name": "lego" };
const update = {
"$set": {
"name": "blocks",
"price": 20.99,
"category": "toys"
}
};
const options = { "upsert": false };
itemsCollection.updateOne(query, update, options)
.then(result => {
const { matchedCount, modifiedCount } = result;
if(matchedCount && modifiedCount) {
console.log(`Successfully updated the item.`)
}
})
.catch(err => console.error(`Failed to update the item: ${err}`))
9:

const doc1 = { "name": "basketball", "category": "sports", "quantity": 20, "reviews": [] };
const doc2 = { "name": "football", "category": "sports", "quantity": 30, "reviews": [] };
return itemsCollection.insertMany([doc1, doc2])
.then(result => {
console.log(`Successfully inserted ${result.insertedIds.length} items!`);
return result
})
.catch(err => console.error(`Failed to insert documents: ${err}`))

Cập nhật các hoạt động tìm các tài liệu hiện có trong bộ sưu tập MongoDB và sửa đổi dữ liệu của họ. Bạn sử dụng Cú pháp truy vấn MongoDB tiêu chuẩn để chỉ định tài liệu nào để cập nhật và cập nhật các nhà khai thác để mô tả các thay đổi để áp dụng cho các tài liệu phù hợp.update operators to describe the changes to apply to matching documents.

Ghi chú

Các ví dụ trên trang này sử dụng một bộ sưu tập có tên

const query = { "name": "lego" };
const update = {
"$set": {
"name": "blocks",
"price": 20.99,
"category": "toys"
}
};
const options = { "upsert": false };
itemsCollection.updateOne(query, update, options)
.then(result => {
const { matchedCount, modifiedCount } = result;
if(matchedCount && modifiedCount) {
console.log(`Successfully updated the item.`)
}
})
.catch(err => console.error(`Failed to update the item: ${err}`))
4 mô hình các mặt hàng khác nhau có sẵn để mua trong một cửa hàng trực tuyến. Mỗi mặt hàng có
const query = { "name": "lego" };
const update = {
"$set": {
"name": "blocks",
"price": 20.99,
"category": "toys"
}
};
const options = { "upsert": false };
itemsCollection.updateOne(query, update, options)
.then(result => {
const { matchedCount, modifiedCount } = result;
if(matchedCount && modifiedCount) {
console.log(`Successfully updated the item.`)
}
})
.catch(err => console.error(`Failed to update the item: ${err}`))
5, hàng tồn kho
const query = { "name": "lego" };
const update = {
"$set": {
"name": "blocks",
"price": 20.99,
"category": "toys"
}
};
const options = { "upsert": false };
itemsCollection.updateOne(query, update, options)
.then(result => {
const { matchedCount, modifiedCount } = result;
if(matchedCount && modifiedCount) {
console.log(`Successfully updated the item.`)
}
})
.catch(err => console.error(`Failed to update the item: ${err}`))
6 và một loạt khách hàng
const query = { "name": "lego" };
const update = {
"$set": {
"name": "blocks",
"price": 20.99,
"category": "toys"
}
};
const options = { "upsert": false };
itemsCollection.updateOne(query, update, options)
.then(result => {
const { matchedCount, modifiedCount } = result;
if(matchedCount && modifiedCount) {
console.log(`Successfully updated the item.`)
}
})
.catch(err => console.error(`Failed to update the item: ${err}`))
7.

Lược đồ JSON cho Store.Items

Để sử dụng đoạn mã trong một hàm, trước tiên bạn phải khởi tạo một tay cầm bộ sưu tập MongoDB:

const query = { "name": "lego" };
const update = {
"$set": {
"name": "blocks",
"price": 20.99,
"category": "toys"
}
};
const options = { "upsert": false };
itemsCollection.updateOne(query, update, options)
.then(result => {
const { matchedCount, modifiedCount } = result;
if(matchedCount && modifiedCount) {
console.log(`Successfully updated the item.`)
}
})
.catch(err => console.error(`Failed to update the item: ${err}`))

Bạn có thể cập nhật nhiều tài liệu trong một bộ sưu tập bằng phương pháp

const query = { "name": "board games" };
const update = { "$inc": { "quantity": 5 } };
const options = { "upsert": true };
itemsCollection.updateOne(query, update, options)
.then(result => {
const { matchedCount, modifiedCount, upsertedId } = result;
if(upsertedId) {
console.log(`Document not found. Inserted a new document with _id: ${upsertedId}`)
} else {
console.log(`Successfully increased ${query.name} quantity by ${update.$inc.quantity}`)
}
})
.catch(err => console.error(`Failed to upsert document: ${err}`))
0.

Đoạn trích chức năng sau đây cập nhật tất cả các tài liệu trong bộ sưu tập

const query = { "name": "lego" };
const update = {
"$set": {
"name": "blocks",
"price": 20.99,
"category": "toys"
}
};
const options = { "upsert": false };
itemsCollection.updateOne(query, update, options)
.then(result => {
const { matchedCount, modifiedCount } = result;
if(matchedCount && modifiedCount) {
console.log(`Successfully updated the item.`)
}
})
.catch(err => console.error(`Failed to update the item: ${err}`))
9 bằng cách nhân các giá trị
const query = { "name": "lego" };
const update = {
"$set": {
"name": "blocks",
"price": 20.99,
"category": "toys"
}
};
const options = { "upsert": false };
itemsCollection.updateOne(query, update, options)
.then(result => {
const { matchedCount, modifiedCount } = result;
if(matchedCount && modifiedCount) {
console.log(`Successfully updated the item.`)
}
})
.catch(err => console.error(`Failed to update the item: ${err}`))
6 của chúng với
const query = { "name": "board games" };
const update = { "$inc": { "quantity": 5 } };
const options = { "upsert": true };
itemsCollection.updateOne(query, update, options)
.then(result => {
const { matchedCount, modifiedCount, upsertedId } = result;
if(upsertedId) {
console.log(`Document not found. Inserted a new document with _id: ${upsertedId}`)
} else {
console.log(`Successfully increased ${query.name} quantity by ${update.$inc.quantity}`)
}
})
.catch(err => console.error(`Failed to upsert document: ${err}`))
3:

const query = {};
const update = { "$mul": { "quantity": 10 } };
const options = { "upsert": false }
return itemsCollection.updateMany(query, update, options)
.then(result => {
const { matchedCount, modifiedCount } = result;
console.log(`Successfully matched ${matchedCount} and modified ${modifiedCount} items.`)
return result
})
.catch(err => console.error(`Failed to update items: ${err}`))

Nếu một thao tác cập nhật không khớp với bất kỳ tài liệu nào trong bộ sưu tập, bạn có thể tự động chèn một tài liệu mới duy nhất vào bộ sưu tập phù hợp với truy vấn cập nhật bằng cách đặt tùy chọn

const query = { "name": "board games" };
const update = { "$inc": { "quantity": 5 } };
const options = { "upsert": true };
itemsCollection.updateOne(query, update, options)
.then(result => {
const { matchedCount, modifiedCount, upsertedId } = result;
if(upsertedId) {
console.log(`Document not found. Inserted a new document with _id: ${upsertedId}`)
} else {
console.log(`Successfully increased ${query.name} quantity by ${update.$inc.quantity}`)
}
})
.catch(err => console.error(`Failed to upsert document: ${err}`))
4 thành
const query = { "name": "board games" };
const update = { "$inc": { "quantity": 5 } };
const options = { "upsert": true };
itemsCollection.updateOne(query, update, options)
.then(result => {
const { matchedCount, modifiedCount, upsertedId } = result;
if(upsertedId) {
console.log(`Document not found. Inserted a new document with _id: ${upsertedId}`)
} else {
console.log(`Successfully increased ${query.name} quantity by ${update.$inc.quantity}`)
}
})
.catch(err => console.error(`Failed to upsert document: ${err}`))
5.

Đoạn trích chức năng sau đây cập nhật một tài liệu trong bộ sưu tập

const query = { "name": "lego" };
const update = {
"$set": {
"name": "blocks",
"price": 20.99,
"category": "toys"
}
};
const options = { "upsert": false };
itemsCollection.updateOne(query, update, options)
.then(result => {
const { matchedCount, modifiedCount } = result;
if(matchedCount && modifiedCount) {
console.log(`Successfully updated the item.`)
}
})
.catch(err => console.error(`Failed to update the item: ${err}`))
9 có
const query = { "name": "lego" };
const update = {
"$set": {
"name": "blocks",
"price": 20.99,
"category": "toys"
}
};
const options = { "upsert": false };
itemsCollection.updateOne(query, update, options)
.then(result => {
const { matchedCount, modifiedCount } = result;
if(matchedCount && modifiedCount) {
console.log(`Successfully updated the item.`)
}
})
.catch(err => console.error(`Failed to update the item: ${err}`))
5 của
const query = { "name": "board games" };
const update = { "$inc": { "quantity": 5 } };
const options = { "upsert": true };
itemsCollection.updateOne(query, update, options)
.then(result => {
const { matchedCount, modifiedCount, upsertedId } = result;
if(upsertedId) {
console.log(`Document not found. Inserted a new document with _id: ${upsertedId}`)
} else {
console.log(`Successfully increased ${query.name} quantity by ${update.$inc.quantity}`)
}
})
.catch(err => console.error(`Failed to upsert document: ${err}`))
8 bằng cách tăng
const query = { "name": "lego" };
const update = {
"$set": {
"name": "blocks",
"price": 20.99,
"category": "toys"
}
};
const options = { "upsert": false };
itemsCollection.updateOne(query, update, options)
.then(result => {
const { matchedCount, modifiedCount } = result;
if(matchedCount && modifiedCount) {
console.log(`Successfully updated the item.`)
}
})
.catch(err => console.error(`Failed to update the item: ${err}`))
6 của nó vào

{ "$set": { "": <Value>, ... } }

0. Tùy chọn
const query = { "name": "board games" };
const update = { "$inc": { "quantity": 5 } };
const options = { "upsert": true };
itemsCollection.updateOne(query, update, options)
.then(result => {
const { matchedCount, modifiedCount, upsertedId } = result;
if(upsertedId) {
console.log(`Document not found. Inserted a new document with _id: ${upsertedId}`)
} else {
console.log(`Successfully increased ${query.name} quantity by ${update.$inc.quantity}`)
}
})
.catch(err => console.error(`Failed to upsert document: ${err}`))
4 được bật, vì vậy nếu không có tài liệu nào có giá trị
const query = { "name": "lego" };
const update = {
"$set": {
"name": "blocks",
"price": 20.99,
"category": "toys"
}
};
const options = { "upsert": false };
itemsCollection.updateOne(query, update, options)
.then(result => {
const { matchedCount, modifiedCount } = result;
if(matchedCount && modifiedCount) {
console.log(`Successfully updated the item.`)
}
})
.catch(err => console.error(`Failed to update the item: ${err}`))
5 là

{ "$set": { "": <Value>, ... } }

3 thì MongoDB sẽ chèn một tài liệu mới với trường
const query = { "name": "lego" };
const update = {
"$set": {
"name": "blocks",
"price": 20.99,
"category": "toys"
}
};
const options = { "upsert": false };
itemsCollection.updateOne(query, update, options)
.then(result => {
const { matchedCount, modifiedCount } = result;
if(matchedCount && modifiedCount) {
console.log(`Successfully updated the item.`)
}
})
.catch(err => console.error(`Failed to update the item: ${err}`))
5 được đặt thành

{ "$set": { "": <Value>, ... } }

5 và giá trị
const query = { "name": "lego" };
const update = {
"$set": {
"name": "blocks",
"price": 20.99,
"category": "toys"
}
};
const options = { "upsert": false };
itemsCollection.updateOne(query, update, options)
.then(result => {
const { matchedCount, modifiedCount } = result;
if(matchedCount && modifiedCount) {
console.log(`Successfully updated the item.`)
}
})
.catch(err => console.error(`Failed to update the item: ${err}`))
6 được đặt thành

{ "$set": { "": <Value>, ... } }

0:

const query = { "name": "board games" };
const update = { "$inc": { "quantity": 5 } };
const options = { "upsert": true };
itemsCollection.updateOne(query, update, options)
.then(result => {
const { matchedCount, modifiedCount, upsertedId } = result;
if(upsertedId) {
console.log(`Document not found. Inserted a new document with _id: ${upsertedId}`)
} else {
console.log(`Successfully increased ${query.name} quantity by ${update.$inc.quantity}`)
}
})
.catch(err => console.error(`Failed to upsert document: ${err}`))

Các toán tử trường cho phép bạn sửa đổi các trường và giá trị của tài liệu.

Bạn có thể sử dụng toán tử $ SET để đặt giá trị của một trường mà không ảnh hưởng đến các trường khác trong tài liệu.$set operator to set the value of a single field without affecting other fields in a document.

{ "$set": { "": <Value>, ... } }

Bạn có thể sử dụng toán tử $ đổi tên để thay đổi tên của một trường trong một tài liệu.$rename operator to change the name of a single field in a document.

{ "$rename": { "": <New Field Name>, ... } }

Bạn có thể sử dụng toán tử $ Inc để thêm một số được chỉ định vào giá trị hiện tại của trường. Số lượng có thể là dương hoặc âm.$inc operator to add a specified number to the current value of a field. The number can be positive or negative.

{ "$inc": { "": <Increment Number>, ... } }

Bạn có thể sử dụng toán tử $ MUL để nhân một số được chỉ định với giá trị hiện tại của trường. Số lượng có thể là dương hoặc âm.$mul operator to multiply a specified number with the current value of a field. The number can be positive or negative.

exports = function() {
const mongodb = context.services.get("mongodb-atlas");
const itemsCollection = mongodb.db("store").collection("items");
const purchasesCollection = mongodb.db("store").collection("purchases");
// ... paste snippet here ...
}
0

Các toán tử mảng cho phép bạn làm việc với các giá trị bên trong các mảng.

Bạn có thể sử dụng toán tử $ Push để thêm giá trị vào cuối trường mảng.$push operator to add a value to the end of an array field.

exports = function() {
const mongodb = context.services.get("mongodb-atlas");
const itemsCollection = mongodb.db("store").collection("items");
const purchasesCollection = mongodb.db("store").collection("purchases");
// ... paste snippet here ...
}
1

Bạn có thể sử dụng toán tử $ pop để xóa phần tử đầu tiên hoặc cuối cùng của trường mảng. Chỉ định

{ "$set": { "": <Value>, ... } }

8 để xóa phần tử đầu tiên và

{ "$set": { "": <Value>, ... } }

9 để loại bỏ phần tử cuối cùng.$pop operator to remove either the first or last element of an array field. Specify

{ "$set": { "": <Value>, ... } }

8 to remove the first element and

{ "$set": { "": <Value>, ... } }

9 to remove the last element.

exports = function() {
const mongodb = context.services.get("mongodb-atlas");
const itemsCollection = mongodb.db("store").collection("items");
const purchasesCollection = mongodb.db("store").collection("purchases");
// ... paste snippet here ...
}
2

Bạn có thể sử dụng toán tử $ addtoset để thêm giá trị vào trường mảng nếu giá trị đó chưa được đưa vào mảng. Nếu giá trị đã có mặt,

{ "$rename": { "": <New Field Name>, ... } }

0 không làm gì cả.$addToSet operator to add a value to an array field if that value is not already included in the array. If the value is already present,

{ "$rename": { "": <New Field Name>, ... } }

0 does nothing.

exports = function() {
const mongodb = context.services.get("mongodb-atlas");
const itemsCollection = mongodb.db("store").collection("items");
const purchasesCollection = mongodb.db("store").collection("purchases");
// ... paste snippet here ...
}
3

Bạn có thể sử dụng toán tử $ kéo để xóa tất cả các phiên bản của bất kỳ giá trị nào khớp với một điều kiện được chỉ định từ trường mảng.$pull operator to remove all instances of any values that match a specified condition from an array field.

exports = function() {
const mongodb = context.services.get("mongodb-atlas");
const itemsCollection = mongodb.db("store").collection("items");
const purchasesCollection = mongodb.db("store").collection("purchases");
// ... paste snippet here ...
}
4

Bạn có thể sử dụng toán tử $ [] (Tất cả cập nhật vị trí) để cập nhật tất cả các phần tử trong trường mảng:$[] (All Positional Update) operator to update all elements in an array field:

Thí dụ

Hãy xem xét một bộ sưu tập

{ "$rename": { "": <New Field Name>, ... } }

1 mô tả từng học sinh trong một lớp. Mỗi tài liệu bao gồm một trường

{ "$rename": { "": <New Field Name>, ... } }

2 chứa một mảng số:

exports = function() {
const mongodb = context.services.get("mongodb-atlas");
const itemsCollection = mongodb.db("store").collection("items");
const purchasesCollection = mongodb.db("store").collection("purchases");
// ... paste snippet here ...
}
5

Hoạt động cập nhật sau đây thêm 10 cho tất cả các giá trị trong mảng

{ "$rename": { "": <New Field Name>, ... } }

2 của mỗi học sinh:

exports = function() {
const mongodb = context.services.get("mongodb-atlas");
const itemsCollection = mongodb.db("store").collection("items");
const purchasesCollection = mongodb.db("store").collection("purchases");
// ... paste snippet here ...
}
6

Sau khi cập nhật, mọi giá trị lớp đã tăng thêm 10:

exports = function() {
const mongodb = context.services.get("mongodb-atlas");
const itemsCollection = mongodb.db("store").collection("items");
const purchasesCollection = mongodb.db("store").collection("purchases");
// ... paste snippet here ...
}
7

Bạn có thể sử dụng toán tử $ [Phần tử] (Cập nhật vị trí) để cập nhật các phần tử cụ thể trong trường Mảng dựa trên bộ lọc mảng:$[element] (Filtered Positional Update) operator to update specific elements in an array field based on an array filter:

Thí dụ

Hãy xem xét một bộ sưu tập

{ "$rename": { "": <New Field Name>, ... } }

1 mô tả từng học sinh trong một lớp. Mỗi tài liệu bao gồm một trường

{ "$rename": { "": <New Field Name>, ... } }

2 chứa một mảng số:

exports = function() {
const mongodb = context.services.get("mongodb-atlas");
const itemsCollection = mongodb.db("store").collection("items");
const purchasesCollection = mongodb.db("store").collection("purchases");
// ... paste snippet here ...
}
7

Hoạt động cập nhật sau đây thêm 10 cho tất cả các giá trị trong mảng

{ "$rename": { "": <New Field Name>, ... } }

2 của mỗi học sinh:

exports = function() {
const mongodb = context.services.get("mongodb-atlas");
const itemsCollection = mongodb.db("store").collection("items");
const purchasesCollection = mongodb.db("store").collection("purchases");
// ... paste snippet here ...
}
9

Sau khi cập nhật, mọi giá trị lớp đã tăng thêm 10:

const newItem = {
"name": "Plastic Bricks",
"quantity": 10,
"category": "toys",
"reviews": [{ "username": "legolover", "comment": "These are awesome!" }]
};
itemsCollection.insertOne(newItem)
.then(result => console.log(`Successfully inserted item with _id: ${result.insertedId}`))
.catch(err => console.error(`Failed to insert item: ${err}`))
0

Bạn có thể sử dụng toán tử $ [Phần tử] (Cập nhật vị trí) để cập nhật các phần tử cụ thể trong trường Mảng dựa trên bộ lọc mảng:

Hãy xem xét một bộ sưu tập

{ "$rename": { "": <New Field Name>, ... } }

1 mô tả từng học sinh trong một lớp. Mỗi tài liệu bao gồm một trường

{ "$rename": { "": <New Field Name>, ... } }

2 chứa một mảng số, một số trong đó lớn hơn 100:

Hoạt động cập nhật sau đây đặt tất cả các giá trị cấp lớn hơn 100 đến chính xác 100:

Sau khi cập nhật, tất cả các giá trị cấp lớn hơn 100 được đặt thành chính xác 100 và tất cả các lớp khác không bị ảnh hưởng:

Xóa hoạt động Tìm các tài liệu hiện có trong bộ sưu tập MongoDB và xóa chúng. Bạn sử dụng Cú pháp truy vấn MongoDB tiêu chuẩn để chỉ định các tài liệu nào để xóa.

Bạn có thể xóa một tài liệu duy nhất từ ​​một bộ sưu tập bằng phương thức

{ "$rename": { "": <New Field Name>, ... } }

6.

const newItem = {
"name": "Plastic Bricks",
"quantity": 10,
"category": "toys",
"reviews": [{ "username": "legolover", "comment": "These are awesome!" }]
};
itemsCollection.insertOne(newItem)
.then(result => console.log(`Successfully inserted item with _id: ${result.insertedId}`))
.catch(err => console.error(`Failed to insert item: ${err}`))
2

Đoạn trích chức năng sau đây xóa một tài liệu trong bộ sưu tập

const query = { "name": "lego" };
const update = {
"$set": {
"name": "blocks",
"price": 20.99,
"category": "toys"
}
};
const options = { "upsert": false };
itemsCollection.updateOne(query, update, options)
.then(result => {
const { matchedCount, modifiedCount } = result;
if(matchedCount && modifiedCount) {
console.log(`Successfully updated the item.`)
}
})
.catch(err => console.error(`Failed to update the item: ${err}`))
9 có giá trị
const query = { "name": "lego" };
const update = {
"$set": {
"name": "blocks",
"price": 20.99,
"category": "toys"
}
};
const options = { "upsert": false };
itemsCollection.updateOne(query, update, options)
.then(result => {
const { matchedCount, modifiedCount } = result;
if(matchedCount && modifiedCount) {
console.log(`Successfully updated the item.`)
}
})
.catch(err => console.error(`Failed to update the item: ${err}`))
5 là
const query = {};
const update = { "$mul": { "quantity": 10 } };
const options = { "upsert": false }
return itemsCollection.updateMany(query, update, options)
.then(result => {
const { matchedCount, modifiedCount } = result;
console.log(`Successfully matched ${matchedCount} and modified ${modifiedCount} items.`)
return result
})
.catch(err => console.error(`Failed to update items: ${err}`))
6:

const newItem = {
"name": "Plastic Bricks",
"quantity": 10,
"category": "toys",
"reviews": [{ "username": "legolover", "comment": "These are awesome!" }]
};
itemsCollection.insertOne(newItem)
.then(result => console.log(`Successfully inserted item with _id: ${result.insertedId}`))
.catch(err => console.error(`Failed to insert item: ${err}`))
3

const newItem = {
"name": "Plastic Bricks",
"quantity": 10,
"category": "toys",
"reviews": [{ "username": "legolover", "comment": "These are awesome!" }]
};
itemsCollection.insertOne(newItem)
.then(result => console.log(`Successfully inserted item with _id: ${result.insertedId}`))
.catch(err => console.error(`Failed to insert item: ${err}`))
1multi-document transactions that let you read and write multiple documents atomically, even across collections.

Bạn có thể xóa nhiều mục khỏi bộ sưu tập bằng phương thức

{ "$inc": { "": <Increment Number>, ... } }

0.

  1. Đoạn trích sau đây xóa tất cả các tài liệu trong bộ sưu tập

    const query = { "name": "lego" };
    const update = {
    "$set": {
    "name": "blocks",
    "price": 20.99,
    "category": "toys"
    }
    };
    const options = { "upsert": false };
    itemsCollection.updateOne(query, update, options)
    .then(result => {
    const { matchedCount, modifiedCount } = result;
    if(matchedCount && modifiedCount) {
    console.log(`Successfully updated the item.`)
    }
    })
    .catch(err => console.error(`Failed to update the item: ${err}`))
    9 không có bất kỳ
    const query = { "name": "lego" };
    const update = {
    "$set": {
    "name": "blocks",
    "price": 20.99,
    "category": "toys"
    }
    };
    const options = { "upsert": false };
    itemsCollection.updateOne(query, update, options)
    .then(result => {
    const { matchedCount, modifiedCount } = result;
    if(matchedCount && modifiedCount) {
    console.log(`Successfully updated the item.`)
    }
    })
    .catch(err => console.error(`Failed to update the item: ${err}`))
    7:

  2. Viết hàng loạt kết hợp nhiều hoạt động ghi vào một thao tác duy nhất. Bạn có thể đưa ra lệnh ghi số lượng lớn bằng phương pháp

    { "$inc": { "": <Increment Number>, ... } }

    3.read and write settings for the transaction.

    const newItem = {
    "name": "Plastic Bricks",
    "quantity": 10,
    "category": "toys",
    "reviews": [{ "username": "legolover", "comment": "These are awesome!" }]
    };
    itemsCollection.insertOne(newItem)
    .then(result => console.log(`Successfully inserted item with _id: ${result.insertedId}`))
    .catch(err => console.error(`Failed to insert item: ${err}`))
    4

  3. MongoDB hỗ trợ các giao dịch đa tài liệu cho phép bạn đọc và viết nhiều tài liệu một cách nguyên tử, ngay cả trên các bộ sưu tập.

    const newItem = {
    "name": "Plastic Bricks",
    "quantity": 10,
    "category": "toys",
    "reviews": [{ "username": "legolover", "comment": "These are awesome!" }]
    };
    itemsCollection.insertOne(newItem)
    .then(result => console.log(`Successfully inserted item with _id: ${result.insertedId}`))
    .catch(err => console.error(`Failed to insert item: ${err}`))
    5

  4. Để thực hiện giao dịch:

    const newItem = {
    "name": "Plastic Bricks",
    "quantity": 10,
    "category": "toys",
    "reviews": [{ "username": "legolover", "comment": "These are awesome!" }]
    };
    itemsCollection.insertOne(newItem)
    .then(result => console.log(`Successfully inserted item with _id: ${result.insertedId}`))
    .catch(err => console.error(`Failed to insert item: ${err}`))
    6

  5. Khi giao dịch hoàn tất, hãy gọi

    { "$inc": { "": <Increment Number>, ... } }

    8 để kết thúc phiên và tài nguyên miễn phí.

    const newItem = {
    "name": "Plastic Bricks",
    "quantity": 10,
    "category": "toys",
    "reviews": [{ "username": "legolover", "comment": "These are awesome!" }]
    };
    itemsCollection.insertOne(newItem)
    .then(result => console.log(`Successfully inserted item with _id: ${result.insertedId}`))
    .catch(err => console.error(`Failed to insert item: ${err}`))
    7

Ví dụ sau đây tạo ra hai người dùng, "Henry" và "Michelle" và sử dụng giao dịch để di chuyển "browniepoints" giữa những người dùng đó về mặt nguyên tử:

const newItem = {
"name": "Plastic Bricks",
"quantity": 10,
"category": "toys",
"reviews": [{ "username": "legolover", "comment": "These are awesome!" }]
};
itemsCollection.insertOne(newItem)
.then(result => console.log(`Successfully inserted item with _id: ${result.insertedId}`))
.catch(err => console.error(`Failed to insert item: ${err}`))
8

Làm thế nào thủ công dữ liệu trong MongoDB?

Để chèn dữ liệu vào Bộ sưu tập MongoDB, bạn cần sử dụng phương thức Chèn () hoặc lưu () của MongoDB.use MongoDB's insert() or save() method.

Làm thế nào thủ công dữ liệu vào la bàn MongoDB?

Để chèn tài liệu vào bộ sưu tập của bạn:..
Nhấp vào Thêm thả xuống dữ liệu và chọn Chèn tài liệu.Bấm để phóng to ..
Chọn chế độ xem phù hợp dựa trên cách bạn muốn chèn tài liệu.Nhấp vào dấu ngoặc {} cho chế độ xem JSON.Đây là chế độ xem mặc định.Nhấp vào biểu tượng Danh sách cho chế độ trường.Bấm để phóng to ..

Chúng ta có thể chèn một tệp trong MongoDB không?

Shell MongoDB cung cấp các phương thức sau để chèn tài liệu vào một bộ sưu tập: Để chèn một tài liệu duy nhất, hãy sử dụng db.collection.insertone ()To insert a single document, use db. collection. insertOne()

Bạn sẽ sử dụng phương pháp nào để chèn một dữ liệu trên MongoDB?

Chèn () chèn một tài liệu duy nhất vào một bộ sưu tập.Ví dụ sau đây chèn một tài liệu mới vào bộ sưu tập hàng tồn kho.Nếu tài liệu không chỉ định trường _ID, MongoDB sẽ thêm trường _id có giá trị ObjectID vào tài liệu mới.