Update Documents更新文件

This page provides examples in:本页提供了以下示例:

This page uses the following mongo shell methods:此页面使用以下mongo shell方法:

The examples on this page use the inventory collection. 本页上的示例使用inventory集合。To create and/or populate the inventory collection, run the following:要创建和/或填充inventory集合,请运行以下操作:

This page uses MongoDB Compass to update the documents.此页面使用MongoDB Compass更新文档。

The examples on this page use the inventory collection. 本页上的示例使用inventory集合。Populate the inventory collection with the following documents:使用以下文档填充inventory集合:

This page uses the following PyMongo Python driver methods:

The examples on this page use the inventory collection. 本页上的示例使用inventory集合。To create and/or populate the inventory collection, run the following:要创建和/或填充inventory集合,请运行以下操作:

This page uses the following Java Synchronous Driver methods:此页面使用以下Java同步驱动程序方法:

The examples on this page use the inventory collection. 本页上的示例使用inventory集合。To create and/or populate the inventory collection, run the following:要创建和/或填充inventory集合,请运行以下操作:

This page uses the following MongoDB Node.js Driver methods:此页面使用以下MongoDB Node.js驱动程序方法:

The examples on this page use the inventory collection. 本页上的示例使用inventory集合。To create and/or populate the inventory collection, run the following:要创建和/或填充inventory集合,请运行以下操作:

This page uses the following MongoDB PHP Library methods:

The examples on this page use the inventory collection. To create and/or populate the inventory collection, run the following:

This page uses the following Motor driver methods:

  • motor.motor_asyncio.AsyncIOMotorCollection.update_one()
  • motor.motor_asyncio.AsyncIOMotorCollection.update_many()
  • motor.motor_asyncio.AsyncIOMotorCollection.replace_one()

The examples on this page use the inventory collection. To create and/or populate the inventory collection, run the following:

This page uses the following Java Reactive Streams Driver methods:此页面使用以下Java反应流驱动程序方法:

The examples on this page use the inventory collection. 本页上的示例使用inventory集合。To create and/or populate the inventory collection, run the following:要创建和/或填充inventory集合,请运行以下操作:

This page uses the following MongoDB C# Driver methods:

The examples on this page use the inventory collection. To create and/or populate the inventory collection, run the following:

This page uses the following MongoDB Perl Driver methods:

The examples on this page use the inventory collection. To create and/or populate the inventory collection, run the following:

This page uses the following MongoDB Ruby Driver methods:

The examples on this page use the inventory collection. To create and/or populate the inventory collection, run the following:

This page uses the following MongoDB Scala Driver methods:

The examples on this page use the inventory collection. To create and/or populate the inventory collection, run the following:

This page uses the following MongoDB Go Driver functions:

The examples on this page use the inventory collection. To create and/or populate the inventory collection, run the following:

db.inventory.insertMany( [
   { item: "canvas", qty: 100, size: { h: 28, w: 35.5, uom: "cm" }, status: "A" },
   { item: "journal", qty: 25, size: { h: 14, w: 21, uom: "cm" }, status: "A" },
   { item: "mat", qty: 85, size: { h: 27.9, w: 35.5, uom: "cm" }, status: "A" },
   { item: "mousepad", qty: 25, size: { h: 19, w: 22.85, uom: "cm" }, status: "P" },
   { item: "notebook", qty: 50, size: { h: 8.5, w: 11, uom: "in" }, status: "P" },
   { item: "paper", qty: 100, size: { h: 8.5, w: 11, uom: "in" }, status: "D" },
   { item: "planner", qty: 75, size: { h: 22.85, w: 30, uom: "cm" }, status: "D" },
   { item: "postcard", qty: 45, size: { h: 10, w: 15.25, uom: "cm" }, status: "A" },
   { item: "sketchbook", qty: 80, size: { h: 14, w: 21, uom: "cm" }, status: "A" },
   { item: "sketch pad", qty: 95, size: { h: 22.85, w: 30.5, uom: "cm" }, status: "A" }
] );

You can run the operation in the web shell below:您可以在下面的web shell中运行该操作:

[
   { item: "canvas", qty: 100, size: { h: 28, w: 35.5, uom: "cm" }, status: "A" },
   { item: "journal", qty: 25, size: { h: 14, w: 21, uom: "cm" }, status: "A" },
   { item: "mat", qty: 85, size: { h: 27.9, w: 35.5, uom: "cm" }, status: "A" },
   { item: "mousepad", qty: 25, size: { h: 19, w: 22.85, uom: "cm" }, status: "P" },
   { item: "notebook", qty: 50, size: { h: 8.5, w: 11, uom: "in" }, status: "P" },
   { item: "paper", qty: 100, size: { h: 8.5, w: 11, uom: "in" }, status: "D" },
   { item: "planner", qty: 75, size: { h: 22.85, w: 30, uom: "cm" }, status: "D" },
   { item: "postcard", qty: 45, size: { h: 10, w: 15.25, uom: "cm" }, status: "A" },
   { item: "sketchbook", qty: 80, size: { h: 14, w: 21, uom: "cm" }, status: "A" },
   { item: "sketch pad", qty: 95, size: { h: 22.85, w: 30.5, uom: "cm" }, status: "A" }
]

For instructions on inserting documents using MongoDB Compass, see Insert Documents.有关使用MongoDB Compass插入文档的说明,请参阅插入文档

db.inventory.insert_many([
    {"item": "canvas",
     "qty": 100,
     "size": {"h": 28, "w": 35.5, "uom": "cm"},
     "status": "A"},
    {"item": "journal",
     "qty": 25,
     "size": {"h": 14, "w": 21, "uom": "cm"},
     "status": "A"},
    {"item": "mat",
     "qty": 85,
     "size": {"h": 27.9, "w": 35.5, "uom": "cm"},
     "status": "A"},
    {"item": "mousepad",
     "qty": 25,
     "size": {"h": 19, "w": 22.85, "uom": "cm"},
     "status": "P"},
    {"item": "notebook",
     "qty": 50,
     "size": {"h": 8.5, "w": 11, "uom": "in"},
     "status": "P"},
    {"item": "paper",
     "qty": 100,
     "size": {"h": 8.5, "w": 11, "uom": "in"},
     "status": "D"},
    {"item": "planner",
     "qty": 75,
     "size": {"h": 22.85, "w": 30, "uom": "cm"},
     "status": "D"},
    {"item": "postcard",
     "qty": 45,
     "size": {"h": 10, "w": 15.25, "uom": "cm"},
     "status": "A"},
    {"item": "sketchbook",
     "qty": 80,
     "size": {"h": 14, "w": 21, "uom": "cm"},
     "status": "A"},
    {"item": "sketch pad",
     "qty": 95,
     "size": {"h": 22.85, "w": 30.5, "uom": "cm"},
     "status": "A"}])
collection.insertMany(asList(
        Document.parse("{ item: 'canvas', qty: 100, size: { h: 28, w: 35.5, uom: 'cm' }, status: 'A' }"),
        Document.parse("{ item: 'journal', qty: 25, size: { h: 14, w: 21, uom: 'cm' }, status: 'A' }"),
        Document.parse("{ item: 'mat', qty: 85, size: { h: 27.9, w: 35.5, uom: 'cm' }, status: 'A' }"),
        Document.parse("{ item: 'mousepad', qty: 25, size: { h: 19, w: 22.85, uom: 'cm' }, status: 'P' }"),
        Document.parse("{ item: 'notebook', qty: 50, size: { h: 8.5, w: 11, uom: 'in' }, status: 'P' }"),
        Document.parse("{ item: 'paper', qty: 100, size: { h: 8.5, w: 11, uom: 'in' }, status: 'D' }"),
        Document.parse("{ item: 'planner', qty: 75, size: { h: 22.85, w: 30, uom: 'cm' }, status: 'D' }"),
        Document.parse("{ item: 'postcard', qty: 45, size: { h: 10, w: 15.25, uom: 'cm' }, status: 'A' }"),
        Document.parse("{ item: 'sketchbook', qty: 80, size: { h: 14, w: 21, uom: 'cm' }, status: 'A' }"),
        Document.parse("{ item: 'sketch pad', qty: 95, size: { h: 22.85, w: 30.5, uom: 'cm' }, status: 'A' }")
));
await db.collection('inventory').insertMany([
  {
    item: 'canvas',
    qty: 100,
    size: { h: 28, w: 35.5, uom: 'cm' },
    status: 'A'
  },
  {
    item: 'journal',
    qty: 25,
    size: { h: 14, w: 21, uom: 'cm' },
    status: 'A'
  },
  {
    item: 'mat',
    qty: 85,
    size: { h: 27.9, w: 35.5, uom: 'cm' },
    status: 'A'
  },
  {
    item: 'mousepad',
    qty: 25,
    size: { h: 19, w: 22.85, uom: 'cm' },
    status: 'P'
  },
  {
    item: 'notebook',
    qty: 50,
    size: { h: 8.5, w: 11, uom: 'in' },
    status: 'P'
  },
  {
    item: 'paper',
    qty: 100,
    size: { h: 8.5, w: 11, uom: 'in' },
    status: 'D'
  },
  {
    item: 'planner',
    qty: 75,
    size: { h: 22.85, w: 30, uom: 'cm' },
    status: 'D'
  },
  {
    item: 'postcard',
    qty: 45,
    size: { h: 10, w: 15.25, uom: 'cm' },
    status: 'A'
  },
  {
    item: 'sketchbook',
    qty: 80,
    size: { h: 14, w: 21, uom: 'cm' },
    status: 'A'
  },
  {
    item: 'sketch pad',
    qty: 95,
    size: { h: 22.85, w: 30.5, uom: 'cm' },
    status: 'A'
  }
]);
$insertManyResult = $db->inventory->insertMany([
    [
        'item' => 'canvas',
        'qty' => 100,
        'size' => ['h' => 28, 'w' => 35.5, 'uom' => 'cm'],
        'status' => 'A',
    ],
    [
        'item' => 'journal',
        'qty' => 25,
        'size' => ['h' => 14, 'w' => 21, 'uom' => 'cm'],
        'status' => 'A',
    ],
    [
        'item' => 'mat',
        'qty' => 85,
        'size' => ['h' => 27.9, 'w' => 35.5, 'uom' => 'cm'],
        'status' => 'A',
    ],
    [
        'item' => 'mousepad',
        'qty' => 25,
        'size' => ['h' => 19, 'w' => 22.85, 'uom' => 'cm'],
        'status' => 'P',
    ],
    [
        'item' => 'notebook',
        'qty' => 50,
        'size' => ['h' => 8.5, 'w' => 11, 'uom' => 'in'],
        'status' => 'P',
    ],
    [
        'item' => 'paper',
        'qty' => 100,
        'size' => ['h' => 8.5, 'w' => 11, 'uom' => 'in'],
        'status' => 'D',
    ],
    [
        'item' => 'planner',
        'qty' => 75,
        'size' => ['h' => 22.85, 'w' => 30, 'uom' => 'cm'],
        'status' => 'D',
    ],
    [
        'item' => 'postcard',
        'qty' => 45,
        'size' => ['h' => 10, 'w' => 15.25, 'uom' => 'cm'],
        'status' => 'A',
    ],
    [
        'item' => 'sketchbook',
        'qty' => 80,
        'size' => ['h' => 14, 'w' => 21, 'uom' => 'cm'],
        'status' => 'A',
    ],
    [
        'item' => 'sketch pad',
        'qty' => 95,
        'size' => ['h' => 22.85, 'w' => 30.5, 'uom' => 'cm'],
        'status' => 'A',
    ],
]);
await db.inventory.insert_many([
    {"item": "canvas",
     "qty": 100,
     "size": {"h": 28, "w": 35.5, "uom": "cm"},
     "status": "A"},
    {"item": "journal",
     "qty": 25,
     "size": {"h": 14, "w": 21, "uom": "cm"},
     "status": "A"},
    {"item": "mat",
     "qty": 85,
     "size": {"h": 27.9, "w": 35.5, "uom": "cm"},
     "status": "A"},
    {"item": "mousepad",
     "qty": 25,
     "size": {"h": 19, "w": 22.85, "uom": "cm"},
     "status": "P"},
    {"item": "notebook",
     "qty": 50,
     "size": {"h": 8.5, "w": 11, "uom": "in"},
     "status": "P"},
    {"item": "paper",
     "qty": 100,
     "size": {"h": 8.5, "w": 11, "uom": "in"},
     "status": "D"},
    {"item": "planner",
     "qty": 75,
     "size": {"h": 22.85, "w": 30, "uom": "cm"},
     "status": "D"},
    {"item": "postcard",
     "qty": 45,
     "size": {"h": 10, "w": 15.25, "uom": "cm"},
     "status": "A"},
    {"item": "sketchbook",
     "qty": 80,
     "size": {"h": 14, "w": 21, "uom": "cm"},
     "status": "A"},
    {"item": "sketch pad",
     "qty": 95,
     "size": {"h": 22.85, "w": 30.5, "uom": "cm"},
     "status": "A"}])
Publisher<Success> insertManyPublisher = collection.insertMany(asList(
        Document.parse("{ item: 'canvas', qty: 100, size: { h: 28, w: 35.5, uom: 'cm' }, status: 'A' }"),
        Document.parse("{ item: 'journal', qty: 25, size: { h: 14, w: 21, uom: 'cm' }, status: 'A' }"),
        Document.parse("{ item: 'mat', qty: 85, size: { h: 27.9, w: 35.5, uom: 'cm' }, status: 'A' }"),
        Document.parse("{ item: 'mousepad', qty: 25, size: { h: 19, w: 22.85, uom: 'cm' }, status: 'P' }"),
        Document.parse("{ item: 'notebook', qty: 50, size: { h: 8.5, w: 11, uom: 'in' }, status: 'P' }"),
        Document.parse("{ item: 'paper', qty: 100, size: { h: 8.5, w: 11, uom: 'in' }, status: 'D' }"),
        Document.parse("{ item: 'planner', qty: 75, size: { h: 22.85, w: 30, uom: 'cm' }, status: 'D' }"),
        Document.parse("{ item: 'postcard', qty: 45, size: { h: 10, w: 15.25, uom: 'cm' }, status: 'A' }"),
        Document.parse("{ item: 'sketchbook', qty: 80, size: { h: 14, w: 21, uom: 'cm' }, status: 'A' }"),
        Document.parse("{ item: 'sketch pad', qty: 95, size: { h: 22.85, w: 30.5, uom: 'cm' }, status: 'A' }")
));
var documents = new[]
{
    new BsonDocument
    {
        { "item", "canvas" },
        { "qty", 100 },
        { "size", new BsonDocument { { "h", 28 }, { "w", 35.5 }, { "uom", "cm" } } },
        { "status", "A" }
    },
    new BsonDocument
    {
        { "item", "journal" },
        { "qty", 25 },
        { "size", new BsonDocument { { "h", 14 }, { "w", 21 }, { "uom", "cm" } } },
        { "status", "A" }
    },
    new BsonDocument
    {
        { "item", "mat" },
        { "qty", 85 },
        { "size", new BsonDocument { { "h", 27.9 }, { "w", 35.5 }, { "uom", "cm" } } },
        { "status", "A" }
    },
    new BsonDocument
    {
        { "item", "mousepad" },
        { "qty", 25 },
        { "size", new BsonDocument { { "h", 19 }, { "w", 22.85 }, { "uom", "cm" } } },
        { "status", "P" }
    },
    new BsonDocument
    {
        { "item", "notebook" },
        { "qty", 50 },
        { "size", new BsonDocument { { "h", 8.5 }, { "w", 11 }, { "uom", "in" } } },
        { "status", "P" } },
    new BsonDocument
    {
        { "item", "paper" },
        { "qty", 100 },
        { "size", new BsonDocument { { "h", 8.5 }, { "w", 11 }, { "uom", "in" } } },
        { "status", "D" }
    },
    new BsonDocument
    {
        { "item", "planner" },
        { "qty", 75 },
        { "size", new BsonDocument { { "h", 22.85 }, { "w", 30 }, { "uom", "cm" } } },
        { "status", "D" }
    },
    new BsonDocument
    {
        { "item", "postcard" },
        { "qty", 45 },
        { "size", new BsonDocument { { "h", 10 }, { "w", 15.25 }, { "uom", "cm" } } },
        { "status", "A" }
    },
    new BsonDocument
    {
        { "item", "sketchbook" },
        { "qty", 80 },
        { "size", new BsonDocument { { "h", 14 }, { "w", 21 }, { "uom", "cm" } } },
        { "status", "A" }
    },
    new BsonDocument
    {
        { "item", "sketch pad" },
        { "qty", 95 },
        { "size", new BsonDocument { { "h", 22.85 }, { "w", 30.5 }, { "uom", "cm" } } }, { "status", "A" } },
};
collection.InsertMany(documents);
$db->coll("inventory")->insert_many(
    [
        {
            item   => "canvas",
            qty    => 100,
            size   => { h => 28, w => 35.5, uom => "cm" },
            status => "A"
        },
        {
            item   => "journal",
            qty    => 25,
            size   => { h => 14, w => 21, uom => "cm" },
            status => "A"
        },
        {
            item   => "mat",
            qty    => 85,
            size   => { h => 27.9, w => 35.5, uom => "cm" },
            status => "A"
        },
        {
            item   => "mousepad",
            qty    => 25,
            size   => { h => 19, w => 22.85, uom => "cm" },
            status => "P"
        },
        {
            item   => "notebook",
            qty    => 50,
            size   => { h => 8.5, w => 11, uom => "in" },
            status => "P"
        },
        {
            item   => "paper",
            qty    => 100,
            size   => { h => 8.5, w => 11, uom => "in" },
            status => "D"
        },
        {
            item   => "planner",
            qty    => 75,
            size   => { h => 22.85, w => 30, uom => "cm" },
            status => "D"
        },
        {
            item   => "postcard",
            qty    => 45,
            size   => { h => 10, w => 15.25, uom => "cm" },
            status => "A"
        },
        {
            item   => "sketchbook",
            qty    => 80,
            size   => { h => 14, w => 21, uom => "cm" },
            status => "A"
        },
        {
            item   => "sketch pad",
            qty    => 95,
            size   => { h => 22.85, w => 30.5, uom => "cm" },
            status => "A"
        }
    ]
);
client[:inventory].insert_many([
                                { item: 'canvas',
                                  qty: 100,
                                  size: { h: 28, w: 35.5, uom: 'cm' },
                                  status: 'A' },
                                { item: 'journal',
                                  qty: 25,
                                  size: { h: 14, w: 21, uom: 'cm' },
                                  status: 'A' },
                                { item: 'mat',
                                  qty: 85,
                                  size: { h: 27.9, w: 35.5, uom: 'cm' },
                                  status: 'A' },
                                { item: 'mousepad',
                                  qty: 25,
                                  size: { h: 19, w: 22.85, uom: 'cm' },
                                  status: 'P' },
                                { item: 'notebook',
                                  qty: 50,
                                  size: { h: 8.5, w: 11, uom: 'in' },
                                  status: 'P' },
                                { item: 'paper',
                                  qty: 100,
                                  size: { h: 8.5, w: 11, uom: 'in' },
                                  status: 'D' },
                                { item: 'planner',
                                  qty: 75,
                                  size: { h: 22.85, w: 30, uom: 'cm' },
                                  status: 'D' },
                                { item: 'postcard',
                                  qty: 45,
                                  size: { h: 10, w: 15.25, uom: 'cm' },
                                  status: 'A' },
                                { item: 'sketchbook',
                                  qty: 80,
                                  size: { h: 14, w: 21, uom: 'cm' },
                                  status: 'A' },
                                { item: 'sketch pad',
                                  qty: 95,
                                  size: { h: 22.85, w: 30.5, uom: 'cm' },
                                  status: 'A' }
                              ])
collection.insertMany(Seq(
  Document("""{ item: "canvas", qty: 100, size: { h: 28, w: 35.5, uom: "cm" }, status: "A" }"""),
  Document("""{ item: "journal", qty: 25, size: { h: 14, w: 21, uom: "cm" }, status: "A" }"""),
  Document("""{ item: "mat", qty: 85, size: { h: 27.9, w: 35.5, uom: "cm" }, status: "A" }"""),
  Document("""{ item: "mousepad", qty: 25, size: { h: 19, w: 22.85, uom: "cm" }, status: "P" }"""),
  Document("""{ item: "notebook", qty: 50, size: { h: 8.5, w: 11, uom: "in" }, status: "P" }"""),
  Document("""{ item: "paper", qty: 100, size: { h: 8.5, w: 11, uom: "in" }, status: "D" }"""),
  Document("""{ item: "planner", qty: 75, size: { h: 22.85, w: 30, uom: "cm" }, status: "D" }"""),
  Document("""{ item: "postcard", qty: 45, size: { h: 10, w: 15.25, uom: "cm" }, status: "A" }"""),
  Document("""{ item: "sketchbook", qty: 80, size: { h: 14, w: 21, uom: "cm" }, status: "A" }"""),
  Document("""{ item: "sketch pad", qty: 95, size: { h: 22.85, w: 30.5, uom: "cm" }, status: "A" }""")
)).execute()
docs := []interface{}{
	bson.D{
		{"item", "canvas"},
		{"qty", 100},
		{"size", bson.D{
			{"h", 28},
			{"w", 35.5},
			{"uom", "cm"},
		}},
		{"status", "A"},
	},
	bson.D{
		{"item", "journal"},
		{"qty", 25},
		{"size", bson.D{
			{"h", 14},
			{"w", 21},
			{"uom", "cm"},
		}},
		{"status", "A"},
	},
	bson.D{
		{"item", "mat"},
		{"qty", 85},
		{"size", bson.D{
			{"h", 27.9},
			{"w", 35.5},
			{"uom", "cm"},
		}},
		{"status", "A"},
	},
	bson.D{
		{"item", "mousepad"},
		{"qty", 25},
		{"size", bson.D{
			{"h", 19},
			{"w", 22.85},
			{"uom", "in"},
		}},
		{"status", "P"},
	},
	bson.D{
		{"item", "notebook"},
		{"qty", 50},
		{"size", bson.D{
			{"h", 8.5},
			{"w", 11},
			{"uom", "in"},
		}},
		{"status", "P"},
	},
	bson.D{
		{"item", "paper"},
		{"qty", 100},
		{"size", bson.D{
			{"h", 8.5},
			{"w", 11},
			{"uom", "in"},
		}},
		{"status", "D"},
	},
	bson.D{
		{"item", "planner"},
		{"qty", 75},
		{"size", bson.D{
			{"h", 22.85},
			{"w", 30},
			{"uom", "cm"},
		}},
		{"status", "D"},
	},
	bson.D{
		{"item", "postcard"},
		{"qty", 45},
		{"size", bson.D{
			{"h", 10},
			{"w", 15.25},
			{"uom", "cm"},
		}},
		{"status", "A"},
	},
	bson.D{
		{"item", "sketchbook"},
		{"qty", 80},
		{"size", bson.D{
			{"h", 14},
			{"w", 21},
			{"uom", "cm"},
		}},
		{"status", "A"},
	},
	bson.D{
		{"item", "sketch pad"},
		{"qty", 95},
		{"size", bson.D{
			{"h", 22.85},
			{"w", 30.5},
			{"uom", "cm"},
		}},
		{"status", "A"},
	},
}

result, err := coll.InsertMany(context.Background(), docs)

Update Documents in a Collection更新集合中的文档

To update a document, MongoDB provides update operators, such as $set, to modify field values.为了更新文档,MongoDB提供了更新运算符(如$set)来修改字段值。

To use the update operators, pass to the update methods an update document of the form:要使用更新运算符,请向更新方法传递以下表单的更新文档:

{
  <update operator>: { <field1>: <value1>, ... },
  <update operator>: { <field2>: <value2>, ... },
  ...
}

Some update operators, such as $set, will create the field if the field does not exist. 如果字段不存在,某些更新运算符(如$set)将创建该字段。See the individual update operator reference for details.有关详细信息,请参阅单个更新运算符参考。

To update a document in Compass, hover over the target document and click the pencil icon:要在Compass中更新文档,请将鼠标悬停在目标文档上,然后单击铅笔图标:

Click edit document

After clicking the pencil icon, the document enters edit mode:单击铅笔图标后,文档进入编辑模式:

Document edit mode

You can now change the this document by clicking the item you wish to change and modifying the value.现在,您可以通过单击要更改的项目并修改值来更改此文档。

For detailed instructions on updating documents in Compass, refer to the Compass documentation or follow the example below.有关在Compass中更新文档的详细说明,请参阅Compass文档或遵循以下示例

Once you are satisfied with your changes, click Update to save the updated document.对更改感到满意后,单击“更新”保存更新的文档。

Click Cancel to revert any modifications made to the document and exit edit mode.单击“取消”恢复对文档所做的任何修改并退出编辑模式。

To update a document, MongoDB provides update operators such as $set to modify field values.

To use the update operators, pass to the update methods an update document of the form:要使用更新运算符,请向更新方法传递以下表单的更新文档:

{
  <update operator>: { <field1>: <value1>, ... },
  <update operator>: { <field2>: <value2>, ... },
  ...
}

Some update operators, such as $set, will create the field if the field does not exist. See the individual update operator reference for details.

To update a document, MongoDB provides update operators such as $set to modify field values.为了更新文档,MongoDB提供了更新运算符(如$set)来修改字段值。

The driver provides the com.mongodb.client.model.Updates class to facilitate the creation of update documents. 驱动程序提供com.mongodb.client.model.Updates类,以方便创建更新文档。For example:例如:

combine(set( <field1>, <value1>), set(<field2>, <value2> ) )

For a list of the update helpers, see com.mongodb.client.model.Updates.有关更新帮助程序的列表,请参阅com.mongodb.client.model.Updates

Some update operators, such as $set, will create the field if the field does not exist. 如果字段不存在,某些更新运算符(如$set)将创建该字段。See the individual update operator reference for details.有关详细信息,请参阅单个更新运算符参考。

To update a document, MongoDB provides update operators such as $set to modify field values.为了更新文档,MongoDB提供了更新运算符(如$set)来修改字段值。

To use the update operators, pass to the update methods an update document of the form:要使用更新运算符,请向更新方法传递以下表单的更新文档:

{
  <update operator>: { <field1>: <value1>, ... },
  <update operator>: { <field2>: <value2>, ... },
  ...
}

Some update operators, such as $set, will create the field if the field does not exist. 如果字段不存在,某些更新运算符(如$set)将创建该字段。See the individual update operator reference for details.有关详细信息,请参阅单个更新运算符参考。

To update a document, MongoDB provides update operators such as $set to modify field values.

To use the update operators, pass to the update methods an update document of the form:

[
  <update operator> => [ <field1> => <value1>, ... ],
  <update operator> => [ <field2> => <value2>, ... ],
  ...
]

Some update operators, such as $set, will create the field if the field does not exist. See the individual update operator reference for details.

To update a document, MongoDB provides update operators such as $set to modify field values.

To use the update operators, pass to the update methods an update document of the form:要使用更新运算符,请向更新方法传递以下表单的更新文档:

{
  <update operator>: { <field1>: <value1>, ... },
  <update operator>: { <field2>: <value2>, ... },
  ...
}

Some update operators, such as $set, will create the field if the field does not exist. 如果字段不存在,某些更新运算符(如$set)将创建该字段。See the individual update operator reference for details.有关详细信息,请参阅单个更新运算符参考。

To update a document, MongoDB provides update operators such as $set to modify field values.为了更新文档,MongoDB提供了更新运算符(如$set)来修改字段值。

The driver provides the com.mongodb.client.model.Updates class to facilitate the creation of update documents. 驱动程序提供com.mongodb.client.model.Updates类,以方便创建更新文档。For example:例如:

combine(set( <field1>, <value1>), set(<field2>, <value2> ) )

For a list of the update helpers, see com.mongodb.client.model.Updates.有关更新帮助程序的列表,请参阅com.mongodb.client.model.Updates

Some update operators, such as $set, will create the field if the field does not exist. 如果字段不存在,某些更新运算符(如$set)将创建该字段。See the individual update operator reference for details.有关详细信息,请参阅单个更新运算符参考。

To update a document, MongoDB provides update operators such as $set to modify field values.

To use the update operators, pass to the update methods an update document of the form:

{
  <update operator> => { <field1> => <value1>, ... },
  <update operator> => { <field2> => <value2>, ... },
  ...
}

Some update operators, such as $set, will create the field if the field does not exist. See the individual update operator reference for details.

To update a document, MongoDB provides update operators such as $set to modify field values.

To use the update operators, pass to the update methods an update document of the form:

{
  <update operator> => { <field1> => <value1>, ... },
  <update operator> => { <field2> => <value2>, ... },
  ...
}

Some update operators, such as $set, will create the field if the field does not exist. See the individual update operator reference for details.

To update a document, MongoDB provides update operators such as $set to modify field values.

To use the update operators, pass to the update methods an update document of the form:

{
  <update operator> => { <field1> => <value1>, ... },
  <update operator> => { <field2> => <value2>, ... },
  ...
}

Some update operators, such as $set, will create the field if the field does not exist. See the individual update operator reference for details.

To update a document, MongoDB provides update operators such as $set to modify field values.

To use the update operators, pass to the update methods an update document of the form:

(
  set (<field1>, <value1>),
  set (<field2>, <value2>),
  ...
)

Some update operators, such as $set, will create the field if the field does not exist. See the individual update operator reference for details.

To update a document, MongoDB provides update operators such as $set to modify field values.

Some update operators, such as $set, will create the field if the field does not exist. See the individual update operator reference for details.

Note

Starting in MongoDB 4.2, MongoDB can accept an aggregation pipeline to specify the modifications to make instead of an update document. 从MongoDB 4.2开始,MongoDB可以接受聚合管道来指定要进行的修改,而不是更新文档。See the method reference page for details.有关详细信息,请参阅方法参考页。

Update a Single Document更新单个文档

The following example uses the db.collection.updateOne() method on the inventory collection to update the first document where item equals "paper":下面的示例使用inventory集合上的db.collection.updateOne()方法更新第一个其item等于"paper"的文档:

The following example demonstrates using MongoDB Compass to modify a single document where item: paper in the inventory collection:下面的示例演示如何使用MongoDB Compass修改inventory集合中包含item: paper的单个文档:

Note

This example uses the Compass Table View to modify the document. 本例使用Compass 表格视图修改文档。The editing process using the Compass List View follows a very similar approach.使用Compass列表视图的编辑过程遵循非常类似的方法。

For more information on the differences between Table View and List View in Compass, refer to the Compass documentation.有关Compass中表格视图和列表视图之间差异的更多信息,请参阅Compass文档

The following example uses the update_one() method on the inventory collection to update the first document where item equals "paper":以下示例使用inventory集合上的update_one()方法更新第一个其item等于"paper"的文档:

The following example uses the com.mongodb.client.MongoCollection.updateOne method on the inventory collection to update the first document where item equals "paper":以下示例使用inventory集合上的com.mongodb.client.MongoCollection.updateOne方法更新第一个其item等于"paper"的文档:

The following example uses the Collection.updateOne() method on the inventory collection to update the first document where item equals "paper":以下示例使用inventory集合上的Collection.updateOne()方法更新第一个其item等于"paper"的文档:

The following example uses the updateOne() method on the inventory collection to update the first document where item equals "paper":下面的示例使用inventory集合上的updateOne()方法更新第一个其item等于"paper"的文档:

The following example uses the update_one() method on the inventory collection to update the first document where item equals "paper":

The following example uses the com.mongodb.reactivestreams.client.MongoCollection.updateOne on the inventory collection to update the first document where item equals "paper":以下示例使用inventory集合上的com.mongodb.reactivestreams.client.MongoCollection.updateOne来更新item等于"paper"的第一个文档:

The following example uses the IMongoCollection.UpdateOne() method on the inventory collection to update the first document where item equals "paper":

The following example uses the update_one() method on the inventory collection to update the first document where item equals "paper":

The following example uses the update_one() method on the inventory collection to update the first document where item equals "paper":

The following example uses the updateOne() method on the inventory collection to update the first document where item equals "paper":

The following example uses the Collection.UpdateOne method on the inventory collection to update the first document where item equals "paper":

db.inventory.updateOne(
   { item: "paper" },
   {
     $set: { "size.uom": "cm", status: "P" },
     $currentDate: { lastModified: true }
   }
)

The update operation:更新操作:

  • uses the $set operator to update the value of the size.uom field to "cm" and the value of the status field to "P",使用$set运算符将size.uom字段的值更新为"cm",将status字段的值更新为"P"
  • uses the $currentDate operator to update the value of the lastModified field to the current date. 使用$currentDate运算符将lastModified字段的值更新为当前日期。If lastModified field does not exist, $currentDate will create the field. 如果lastModified字段不存在,$currentDate将创建该字段。See $currentDate for details.有关详细信息,请参阅$currentDate

Modify the target document as follows:按如下方式修改目标文档:

  • Change the status field from D to P.status字段从D更改为P
  • Change the size.uom field from in to cm.size.uom字段从in更改为cm
  • Add a new field called lastModified whose value will be today’s date.添加一个名为lastModified的新字段,其值将是今天的日期。
  1. Click the Table button in the top navigation to access the Table View:单击顶部导航中的“表格”按钮以访问表格视图

    Access Table View
  2. Use the Compass query bar to locate the target document.使用Compass查询栏定位目标文档。

    Copy the following filter document into the query bar and click Find:将以下筛选文档复制到查询栏中,然后单击“查找”:

    { item: "paper" }
    Find Paper document
  3. Hover over the status field and click the pencil icon which appears on the right side of the document to enter edit mode:将鼠标悬停在status字段上,然后单击文档右侧出现的铅笔图标,以进入编辑模式:

    Click edit button
  4. Change the value of the field to "P".将字段的值更改为"P"
  5. Click the Update button below the field to save your changes.单击字段下方的“更新”按钮保存更改。
  6. Hover over the size field and click the outward-pointing arrows which appear on the right side of the field. 将鼠标悬停在size字段上,然后单击字段右侧显示的向外箭头。This opens a new tab which displays the fields within the size object:这将打开一个新选项卡,其中显示size对象中的字段:

    Expand size object
  7. Using the same process outlined in steps 3-5 for editing the status field, change the value of the size.uom field to "cm".使用步骤3-5中概述的编辑status字段的相同过程,将size.uom字段的值更改为"cm"
  8. Click the left-most tab above the table labelled inventory to return to the original table view, which displays the top-level document:单击标有inventory的表格上方最左侧的选项卡,返回原始表格视图,其中显示顶级文档:

    Click inventory tab
  9. Hover over the status field and click the pencil icon which appears on the right side of the document to re-enter edit mode.将鼠标悬停在status字段上,然后单击文档右侧出现的铅笔图标以重新进入编辑模式。
  10. Click inside of the status field and click the plus button icon which appears in the edit menu.单击status字段内部,然后单击“编辑”菜单中显示的“加号”按钮图标。

    Click the Add Field After status button which appears below the plus button:单击加号按钮下方显示的“status后添加字段”按钮:

    Add field after status
  11. Add a new field called lastModified with a value of today’s date. 添加一个名为lastModified的新字段,其值为今天的日期。Set the field type to Date:将字段类型设置为Date

    Submit update
  12. Click the Update button below the field to save your changes.单击字段下方的更新按钮保存更改。

    Note

    Because MongoDB Compass does not support $currentDate or any other Field Update Operators, you must manually enter the date value in Compass.由于MongoDB Compass不支持$currentDate或任何其他字段更新运算符,因此必须在Compass中手动输入日期值。

db.inventory.update_one(
    {"item": "paper"},
    {"$set": {"size.uom": "cm", "status": "P"},
     "$currentDate": {"lastModified": True}})
collection.updateOne(eq("item", "paper"),
        combine(set("size.uom", "cm"), set("status", "P"), currentDate("lastModified")));

The update operation:更新操作:

  • uses the $set operator to update the value of the size.uom field to "cm" and the value of the status field to "P",使用$set运算符将size.uom字段的值更新为"cm",将status字段的值更新为"P"
  • uses the $currentDate operator to update the value of the lastModified field to the current date. 使用$currentDate运算符将lastModified字段的值更新为当前日期。If lastModified field does not exist, $currentDate will create the field. 如果lastModified字段不存在,$currentDate将创建该字段。See $currentDate for details.有关详细信息,请参阅$currentDate
await db.collection('inventory').updateOne(
  { item: 'paper' },
  {
    $set: { 'size.uom': 'cm', status: 'P' },
    $currentDate: { lastModified: true }
  }
);

The update operation:更新操作:

  • uses the $set operator to update the value of the size.uom field to "cm" and the value of the status field to "P",使用$set运算符将size.uom字段的值更新为"cm",将status字段的值更新为"P"
  • uses the $currentDate operator to update the value of the lastModified field to the current date. 使用$currentDate运算符将lastModified字段的值更新为当前日期。If lastModified field does not exist, $currentDate will create the field. 如果lastModified字段不存在,$currentDate将创建该字段。See $currentDate for details.有关详细信息,请参阅$currentDate
$updateResult = $db->inventory->updateOne(
    ['item' => 'paper'],
    [
        '$set' => ['size.uom' => 'cm', 'status' => 'P'],
        '$currentDate' => ['lastModified' => true],
    ]
);

The update operation:更新操作:

  • uses the $set operator to update the value of the size.uom field to "cm" and the value of the status field to "P",使用$set运算符将size.uom字段的值更新为"cm",将status字段的值更新为"P"
  • uses the $currentDate operator to update the value of the lastModified field to the current date. 使用$currentDate运算符将lastModified字段的值更新为当前日期。If lastModified field does not exist, $currentDate will create the field. 如果lastModified字段不存在,$currentDate将创建该字段。See $currentDate for details.有关详细信息,请参阅$currentDate
await db.inventory.update_one(
    {"item": "paper"},
    {"$set": {"size.uom": "cm", "status": "P"},
     "$currentDate": {"lastModified": True}})

The update operation:更新操作:

  • uses the $set operator to update the value of the size.uom field to "cm" and the value of the status field to "P",
  • uses the $currentDate operator to update the value of the lastModified field to the current date. If lastModified field does not exist, $currentDate will create the field. See $currentDate for details.
Publisher<UpdateResult> updateOnePublisher = collection.updateOne(eq("item", "paper"),
        combine(set("size.uom", "cm"), set("status", "P"), currentDate("lastModified")));

The update operation:更新操作:

  • uses the $set operator to update the value of the size.uom field to "cm" and the value of the status field to "P",使用$set运算符将size.uom字段的值更新为"cm",将status字段的值更新为"P"
  • uses the $currentDate operator to update the value of the lastModified field to the current date. 使用$currentDate运算符将lastModified字段的值更新为当前日期。If lastModified field does not exist, $currentDate will create the field. 如果lastModified字段不存在,$currentDate将创建该字段。See $currentDate for details.有关详细信息,请参阅$currentDate
var filter = Builders<BsonDocument>.Filter.Eq("item", "paper");
var update = Builders<BsonDocument>.Update.Set("size.uom", "cm").Set("status", "P").CurrentDate("lastModified");
var result = collection.UpdateOne(filter, update);

The update operation:更新操作:

  • uses the $set operator to update the value of the size.uom field to "cm" and the value of the status field to "P",使用$set运算符将size.uom字段的值更新为"cm",将status字段的值更新为"P"
  • uses the $currentDate operator to update the value of the lastModified field to the current date. If lastModified field does not exist, $currentDate will create the field. See $currentDate for details.
# For boolean values, use boolean.pm for 'true' and 'false'
$db->coll("inventory")->update_one(
    { item => "paper" },
    {
        '$set'         => { "size.uom"   => "cm", status => "P" },
        '$currentDate' => { lastModified => true }
    }
);

The update operation:更新操作:

  • uses the $set operator to update the value of the size.uom field to "cm" and the value of the status field to "P",
  • uses the $currentDate operator to update the value of the lastModified field to the current date. If lastModified field does not exist, $currentDate will create the field. See $currentDate for details.
client[:inventory].update_one({ item: 'paper'},
                              { '$set' => { 'size.uom' => 'cm', 'status' => 'P' },
                                '$currentDate' => { 'lastModified' => true } })

The update operation:更新操作:

  • uses the $set operator to update the value of the size.uom field to "cm" and the value of the status field to "P",
  • uses the $currentDate operator to update the value of the lastModified field to the current date. If lastModified field does not exist, $currentDate will create the field. See $currentDate for details.
collection.updateOne(equal("item", "paper"),
  combine(set("size.uom", "cm"), set("status", "P"), currentDate("lastModified"))
).execute()

The update operation:更新操作:

  • uses the $set operator to update the value of the size.uom field to "cm" and the value of the status field to "P",
  • uses the $currentDate operator to update the value of the lastModified field to the current date. If lastModified field does not exist, $currentDate will create the field. See $currentDate for details.
result, err := coll.UpdateOne(
	context.Background(),
	bson.D{
		{"item", "paper"},
	},
	bson.D{
		{"$set", bson.D{
			{"size.uom", "cm"},
			{"status", "P"},
		}},
		{"$currentDate", bson.D{
			{"lastModified", true},
		}},
	},
)

The update operation:更新操作:

  • uses the $set operator to update the value of the size.uom field to "cm" and the value of the status field to "P",使用$set运算符将size.uom字段的值更新为"cm",将status字段的值更新为"P"
  • uses the $currentDate operator to update the value of the lastModified field to the current date. 使用$currentDate运算符将lastModified字段的值更新为当前日期。If lastModified field does not exist, $currentDate will create the field. 如果lastModified字段不存在,$currentDate将创建该字段。See $currentDate for details.

Update Multiple Documents更新多个文档

New in version 3.2.版本3.2中的新功能。

The following example uses the db.collection.updateMany() method on the inventory collection to update all documents where qty is less than 50:以下示例使用inventory集合上的db.collection.updateMany()方法更新qty小于50的所有文档:

Update Multiple Documents更新多个文档

New in version 3.2.版本3.2中的新功能。

The following example uses the update_many() method on the inventory collection to update all documents where qty is less than 50:

Update Multiple Documents更新多个文档

The following example uses the com.mongodb.client.MongoCollection.updateMany method on the inventory collection to update all documents where qty is less than 50:以下示例使用inventory集合上的com.mongodb.client.MongoCollection.updateMany方法更新qty小于50的所有文档:

Update Multiple Documents更新多个文档

The following example uses the Collection.updateMany() method on the inventory collection to update all documents where qty is less than 50:以下示例使用inventory集合上的Collection.updateMany()方法更新qty小于50的所有文档:

Update Multiple Documents更新多个文档

The following example uses the updateMany() method on the inventory collection to update all documents where qty is less than 50:

Update Multiple Documents更新多个文档

New in version 3.2.版本3.2中的新功能。

The following example uses the update_many() method on the inventory collection to update all documents where qty is less than 50:

Update Multiple Documents更新多个文档

The following example uses the com.mongodb.reactivestreams.client.MongoCollection.updateMany method on the inventory collection to update all documents where qty is less than 50:以下示例使用inventory集合上的com.mongodb.reactivestreams.client.MongoCollection.updateMany方法更新qty小于50的所有文档:

Update Multiple Documents更新多个文档

The following example uses the IMongoCollection.UpdateMany() method on the inventory collection to update all documents where qty is less than 50:

Update Multiple Documents更新多个文档

The following example uses the update_many() method on the inventory collection to update all documents where qty is less than 50:

Update Multiple Documents更新多个文档

The following example uses the update_many() method on the inventory collection to update all documents where qty is less than 50:

Update Multiple Documents更新多个文档

The following example uses the updateMany() method on the inventory collection to update all documents where qty is less than 50:

Update Multiple Documents更新多个文档

The following example uses the Collection.UpdateMany method on the inventory collection to update all documents where qty is less than 50:

db.inventory.updateMany(
   { "qty": { $lt: 50 } },
   {
     $set: { "size.uom": "in", status: "P" },
     $currentDate: { lastModified: true }
   }
)

The update operation:更新操作:

  • uses the $set operator to update the value of the size.uom field to "in" and the value of the status field to "P",使用$set运算符将size.uom字段的值更新为"in",将status字段的值更新为"P"
  • uses the $currentDate operator to update the value of the lastModified field to the current date. 使用$currentDate运算符将lastModified字段的值更新为当前日期。If lastModified field does not exist, $currentDate will create the field. 如果lastModified字段不存在,$currentDate将创建该字段。See $currentDate for details.有关详细信息,请参阅$currentDate
db.inventory.update_many(
    {"qty": {"$lt": 50}},
    {"$set": {"size.uom": "in", "status": "P"},
     "$currentDate": {"lastModified": True}})
collection.updateMany(lt("qty", 50),
        combine(set("size.uom", "in"), set("status", "P"), currentDate("lastModified")));

The update operation:更新操作:

  • uses the $set operator to update the value of the size.uom field to "in" and the value of the status field to "P",使用$set运算符将size.uom字段的值更新为"in",将status字段的值更新为"P"
  • uses the $currentDate operator to update the value of the lastModified field to the current date. 使用$currentDate运算符将lastModified字段的值更新为当前日期。If lastModified field does not exist, $currentDate will create the field. 如果lastModified字段不存在,$currentDate将创建该字段。See $currentDate for details.有关详细信息,请参阅$currentDate
await db.collection('inventory').updateMany(
  { qty: { $lt: 50 } },
  {
    $set: { 'size.uom': 'in', status: 'P' },
    $currentDate: { lastModified: true }
  }
);

The update operation:更新操作:

  • uses the $set operator to update the value of the size.uom field to "in" and the value of the status field to "P",使用$set运算符将size.uom字段的值更新为"in",将status字段的值更新为"P"
  • uses the $currentDate operator to update the value of the lastModified field to the current date. 使用$currentDate运算符将lastModified字段的值更新为当前日期。If lastModified field does not exist, $currentDate will create the field. 如果lastModified字段不存在,$currentDate将创建该字段。See $currentDate for details.有关详细信息,请参阅$currentDate
$updateResult = $db->inventory->updateMany(
    ['qty' => ['$lt' => 50]],
    [
        '$set' => ['size.uom' => 'cm', 'status' => 'P'],
        '$currentDate' => ['lastModified' => true],
    ]
);

The update operation:更新操作:

  • uses the $set operator to update the value of the size.uom field to "in" and the value of the status field to "P",
  • uses the $currentDate operator to update the value of the lastModified field to the current date. If lastModified field does not exist, $currentDate will create the field. See $currentDate for details.
await db.inventory.update_many(
    {"qty": {"$lt": 50}},
    {"$set": {"size.uom": "in", "status": "P"},
     "$currentDate": {"lastModified": True}})

The update operation:更新操作:

  • uses the $set operator to update the value of the size.uom field to "in" and the value of the status field to "P",
  • uses the $currentDate operator to update the value of the lastModified field to the current date. If lastModified field does not exist, $currentDate will create the field. See $currentDate for details.
Publisher<UpdateResult> updateManyPublisher = collection.updateMany(lt("qty", 50),
        combine(set("size.uom", "in"), set("status", "P"), currentDate("lastModified")));

The update operation:更新操作:

  • uses the $set operator to update the value of the size.uom field to "in" and the value of the status field to "P",使用$set运算符将size.uom字段的值更新为"in",将status字段的值更新为"P"
  • uses the $currentDate operator to update the value of the lastModified field to the current date. 使用$currentDate运算符将lastModified字段的值更新为当前日期。If lastModified field does not exist, $currentDate will create the field. 如果lastModified字段不存在,$currentDate将创建该字段。See $currentDate for details.有关详细信息,请参阅$currentDate
var filter = Builders<BsonDocument>.Filter.Lt("qty", 50);
var update = Builders<BsonDocument>.Update.Set("size.uom", "in").Set("status", "P").CurrentDate("lastModified");
var result = collection.UpdateMany(filter, update);

The update operation:更新操作:

  • uses the $set operator to update the value of the size.uom field to "in" and the value of the status field to "P",
  • uses the $currentDate operator to update the value of the lastModified field to the current date. If lastModified field does not exist, $currentDate will create the field. See $currentDate for details.
# For boolean values, use boolean.pm for 'true' and 'false'
$db->coll("inventory")->update_many(
    { qty => { '$lt' => 50 } },
    {
        '$set'         => { "size.uom"   => "in", status => "P" },
        '$currentDate' => { lastModified => true }
    }
);

The update operation:更新操作:

  • uses the $set operator to update the value of the size.uom field to "in" and the value of the status field to "P",
  • uses the $currentDate operator to update the value of the lastModified field to the current date. If lastModified field does not exist, $currentDate will create the field. See $currentDate for details.
client[:inventory].update_many({ qty: { '$lt' => 50 } },
                              { '$set' => { 'size.uom' => 'in', 'status' => 'P' },
                                '$currentDate' => { 'lastModified' => true } })

The update operation:更新操作:

  • uses the $set operator to update the value of the size.uom field to "in" and the value of the status field to "P",
  • uses the $currentDate operator to update the value of the lastModified field to the current date. If lastModified field does not exist, $currentDate will create the field. See $currentDate for details.
collection.updateMany(lt("qty", 50),
  combine(set("size.uom", "in"), set("status", "P"), currentDate("lastModified"))
).execute()

The update operation:更新操作:

  • uses the $set operator to update the value of the size.uom field to "in" and the value of the status field to "P",
  • uses the $currentDate operator to update the value of the lastModified field to the current date. If lastModified field does not exist, $currentDate will create the field. See $currentDate for details.
result, err := coll.UpdateMany(
	context.Background(),
	bson.D{
		{"qty", bson.D{
			{"$lt", 50},
		}},
	},
	bson.D{
		{"$set", bson.D{
			{"size.uom", "cm"},
			{"status", "P"},
		}},
		{"$currentDate", bson.D{
			{"lastModified", true},
		}},
	},
)

The update operation:更新操作:

  • uses the $set operator to update the value of the size.uom field to "in" and the value of the status field to "P",
  • uses the $currentDate operator to update the value of the lastModified field to the current date. If lastModified field does not exist, $currentDate will create the field. See $currentDate for details.

Replace a Document替换一个文档

To replace the entire content of a document except for the _id field, pass an entirely new document as the second argument to db.collection.replaceOne().要替换文档中除_id字段之外的全部内容,请将一个全新文档作为第二个参数传递给db.collection.replaceOne()

When replacing a document, the replacement document must consist of only field/value pairs; i.e. do not include update operators expressions.替换文档时,替换文档必须仅包含字段/值对;亦即,不包括更新运算符表达式。

The replacement document can have different fields from the original document. 替换文档可以具有与原始文档不同的字段。In the replacement document, you can omit the _id field since the _id field is immutable; however, if you do include the _id field, it must have the same value as the current value.在替换文档中,您可以省略_id字段,因为_id字段是不可变的;但是,如果确实包含_id字段,则该字段的值必须与当前值相同。

The following example replaces the first document from the inventory collection where item: "paper":以下示例替换库存集合中的第一个满足item: "paper"的文档:

Replace a Document替换一个文档

To replace the entire content of a document except for the _id field, pass an entirely new document as the second argument to replace_one().要替换文档中除_id字段之外的全部内容,请将一个全新文档作为第二个参数传递给replace_one()

When replacing a document, the replacement document must consist of only field/value pairs; i.e. do not include update operators expressions.替换文档时,替换文档必须仅包含字段/值对;亦即,不包括更新运算符表达式。

The replacement document can have different fields from the original document. 替换文档可以具有与原始文档不同的字段。In the replacement document, you can omit the _id field since the _id field is immutable; however, if you do include the _id field, it must have the same value as the current value.在替换文档中,您可以省略_id字段,因为_id字段是不可变的;但是,如果确实包含_id字段,则该字段的值必须与当前值相同。

The following example replaces the first document from the inventory collection where item: "paper":

Replace a Document替换一个文档

To replace the entire content of a document except for the _id field, pass an entirely new document as the second argument to com.mongodb.client.MongoCollection.replaceOne.要替换文档中除_id字段之外的全部内容,请将全新文档作为第二个参数传递给com.mongodb.client.MongoCollection.replaceOne

When replacing a document, the replacement document must consist of only field/value pairs; i.e. do not include update operators expressions.替换文档时,替换文档必须仅包含字段/值对;亦即,不包括更新运算符表达式。

The replacement document can have different fields from the original document. 替换文档可以具有与原始文档不同的字段。In the replacement document, you can omit the _id field since the _id field is immutable; however, if you do include the _id field, it must have the same value as the current value.在替换文档中,您可以省略_id字段,因为_id字段是不可变的;但是,如果确实包含_id字段,则该字段的值必须与当前值相同。

The following example replaces the first document from the inventory collection where item: "paper":以下示例替换inventory集合中的第一个满足item: "paper"的文档:

Replace a Document替换一个文档

To replace the entire content of a document except for the _id field, pass an entirely new document as the second argument to Collection.replaceOne().要替换文档中除_id字段之外的全部内容,请将全新文档作为第二个参数传递给Collection.replaceOne()

When replacing a document, the replacement document must consist of only field/value pairs; i.e. do not include update operators expressions.替换文档时,替换文档必须仅包含字段/值对;亦即,不包括更新运算符表达式。

The replacement document can have different fields from the original document. 替换文档可以具有与原始文档不同的字段。In the replacement document, you can omit the _id field since the _id field is immutable; however, if you do include the _id field, it must have the same value as the current value.在替换文档中,您可以省略_id字段,因为_id字段是不可变的;但是,如果确实包含_id字段,则该字段的值必须与当前值相同。

The following example replaces the first document from the inventory collection where item: "paper":以下示例替换inventory集合中的第一个满足item: "paper"的文档:

Replace a Document替换一个文档

To replace the entire content of a document except for the _id field, pass an entirely new document as the second argument to replaceOne().

When replacing a document, the replacement document must consist of only field/value pairs; i.e. do not include update operators expressions.

The replacement document can have different fields from the original document. In the replacement document, you can omit the _id field since the _id field is immutable; however, if you do include the _id field, it must have the same value as the current value.

The following example replaces the first document from the inventory collection where item: "paper":

Replace a Document替换一个文档

To replace the entire content of a document except for the _id field, pass an entirely new document as the second argument to replace_one().

When replacing a document, the replacement document must consist of only field/value pairs; i.e. do not include update operators expressions.

The replacement document can have different fields from the original document. In the replacement document, you can omit the _id field since the _id field is immutable; however, if you do include the _id field, it must have the same value as the current value.

The following example replaces the first document from the inventory collection where item: "paper":

Replace a Document替换一个文档

To replace the entire content of a document except for the _id field, pass an entirely new document as the second argument to com.mongodb.reactivestreams.client.MongoCollection.replaceOne.要替换文档中除_id字段之外的全部内容,请将全新文档作为第二个参数传递给com.mongodb.reactivestreams.client.MongoCollection.replaceOne

When replacing a document, the replacement document must consist of only field/value pairs; i.e. do not include update operators expressions.替换文档时,替换文档必须仅包含字段/值对;亦即,不包括更新运算符表达式。

The replacement document can have different fields from the original document. 替换文档可以具有与原始文档不同的字段。In the replacement document, you can omit the _id field since the _id field is immutable; however, if you do include the _id field, it must have the same value as the current value.在替换文档中,您可以省略_id字段,因为_id字段是不可变的;但是,如果确实包含_id字段,则该字段的值必须与当前值相同。

The following example replaces the first document from the inventory collection where item: "paper":以下示例替换inventory集合中的第一个满足item: "paper"的文档:

Replace a Document替换一个文档

To replace the entire content of a document except for the _id field, pass an entirely new document as the second argument to IMongoCollection.ReplaceOne().

When replacing a document, the replacement document must consist of only field/value pairs; i.e. do not include update operators expressions.

The replacement document can have different fields from the original document. In the replacement document, you can omit the _id field since the _id field is immutable; however, if you do include the _id field, it must have the same value as the current value.

The following example replaces the first document from the inventory collection where item: "paper":

Replace a Document替换一个文档

To replace the entire content of a document except for the _id field, pass an entirely new document as the second argument to replace_one().

When replacing a document, the replacement document must consist of only field/value pairs; i.e. do not include update operators expressions.

The replacement document can have different fields from the original document. In the replacement document, you can omit the _id field since the _id field is immutable; however, if you do include the _id field, it must have the same value as the current value.

The following example replaces the first document from the inventory collection where item: "paper":

Replace a Document替换一个文档

To replace the entire content of a document except for the _id field, pass an entirely new document as the second argument to replace_one().

When replacing a document, the replacement document must consist of only field/value pairs; i.e. do not include update operators expressions.

The replacement document can have different fields from the original document. In the replacement document, you can omit the _id field since the _id field is immutable; however, if you do include the _id field, it must have the same value as the current value.

The following example replaces the first document from the inventory collection where item: "paper":

Replace a Document替换一个文档

To replace the entire content of a document except for the _id field, pass an entirely new document as the second argument to replaceOne()

When replacing a document, the replacement document must consist of only field/value pairs; i.e. do not include update operators expressions.

The replacement document can have different fields from the original document. In the replacement document, you can omit the _id field since the _id field is immutable; however, if you do include the _id field, it must have the same value as the current value.

The following example replaces the first document from the inventory collection where item: "paper":

Replace a Document替换一个文档

To replace the entire content of a document except for the _id field, pass an entirely new document as the second argument to Collection.ReplaceOne.

When replacing a document, the replacement document must consist of only field/value pairs; i.e. do not include update operators expressions.

The replacement document can have different fields from the original document. In the replacement document, you can omit the _id field since the _id field is immutable; however, if you do include the _id field, it must have the same value as the current value.

The following example replaces the first document from the inventory collection where item: "paper":

db.inventory.replaceOne(
   { item: "paper" },
   { item: "paper", instock: [ { warehouse: "A", qty: 60 }, { warehouse: "B", qty: 40 } ] }
)
db.inventory.replace_one(
    {"item": "paper"},
    {"item": "paper",
     "instock": [
         {"warehouse": "A", "qty": 60},
         {"warehouse": "B", "qty": 40}]})
collection.replaceOne(eq("item", "paper"),
        Document.parse("{ item: 'paper', instock: [ { warehouse: 'A', qty: 60 }, { warehouse: 'B', qty: 40 } ] }"));
await db.collection('inventory').replaceOne(
  { item: 'paper' },
  {
    item: 'paper',
    instock: [
      { warehouse: 'A', qty: 60 },
      { warehouse: 'B', qty: 40 }
    ]
  }
);
$updateResult = $db->inventory->replaceOne(
    ['item' => 'paper'],
    [
        'item' => 'paper',
        'instock' => [
            ['warehouse' => 'A', 'qty' => 60],
            ['warehouse' => 'B', 'qty' => 40],
        ],
    ]
);
await db.inventory.replace_one(
    {"item": "paper"},
    {"item": "paper",
     "instock": [
         {"warehouse": "A", "qty": 60},
         {"warehouse": "B", "qty": 40}]})
Publisher<UpdateResult> replaceOnePublisher = collection.replaceOne(eq("item", "paper"),
        Document.parse("{ item: 'paper', instock: [ { warehouse: 'A', qty: 60 }, { warehouse: 'B', qty: 40 } ] }"));
var filter = Builders<BsonDocument>.Filter.Eq("item", "paper");
var replacement = new BsonDocument
{
    { "item", "paper" },
    { "instock", new BsonArray
        {
            new BsonDocument { { "warehouse", "A" }, { "qty", 60 } },
            new BsonDocument { { "warehouse", "B" }, { "qty", 40 } } }
        }
};
var result = collection.ReplaceOne(filter, replacement);
$db->coll("inventory")->replace_one(
    { item => "paper" },
    {
        item    => "paper",
        instock => [ { warehouse => "A", qty => 60 }, { warehouse => "B", qty => 40 } ]
    }
);
client[:inventory].replace_one({ item: 'paper' },
                               { item: 'paper',
                                 instock: [ { warehouse: 'A', qty: 60 },
                                            { warehouse: 'B', qty: 40 } ] })
collection.replaceOne(equal("item", "paper"),
  Document("""{ item: "paper", instock: [ { warehouse: "A", qty: 60 }, { warehouse: "B", qty: 40 } ] }""")
).execute()
result, err := coll.ReplaceOne(
	context.Background(),
	bson.D{
		{"item", "paper"},
	},
	bson.D{
		{"item", "paper"},
		{"instock", bson.A{
			bson.D{
				{"warehouse", "A"},
				{"qty", 60},
			},
			bson.D{
				{"warehouse", "B"},
				{"qty", 40},
			},
		}},
	},
)

Behavior行为

Atomicity原子性

All write operations in MongoDB are atomic on the level of a single document. MongoDB中的所有写操作都是单个文档级别的原子操作。For more information on MongoDB and atomicity, see Atomicity and Transactions.有关MongoDB和原子性的更多信息,请参阅原子性和事务

_id Field字段

Once set, you cannot update the value of the _id field nor can you replace an existing document with a replacement document that has a different _id field value.设置后,您无法更新_id字段的值,也无法使用具有不同_id字段值的替换文档替换现有文档。

Field Order字段顺序

MongoDB preserves the order of the document fields following write operations except for the following cases:MongoDB在写操作后保留文档字段的顺序,但以下情况除外:

  • The _id field is always the first field in the document._id字段始终是文档中的第一个字段。
  • Updates that include renaming of field names may result in the reordering of fields in the document.包括renaming字段名的更新可能会导致文档中字段的重新排序。

Upsert Option选项

If updateOne(), updateMany(), or replaceOne() includes upsert : true and no documents match the specified filter, then the operation creates a new document and inserts it. 如果updateOne()updateMany()replaceOne()包含upsert: true且没有与指定筛选器匹配的文档,则该操作将创建一个新文档并将其插入。If there are matching documents, then the operation modifies or replaces the matching document or documents.如果存在匹配文档,则该操作将修改或替换匹配文档。

For details on the new document created, see the individual reference pages for the methods.有关创建的新文档的详细信息,请参阅方法的各个参考页。

Upsert Option选项

If update_one(), update_many(), or replace_one() includes upsert : true and no documents match the specified filter, then the operation creates a new document and inserts it. If there are matching documents, then the operation modifies or replaces the matching document or documents.

For details on the new document created, see the individual reference pages for the methods.有关创建的新文档的详细信息,请参阅方法的各个参考页。

Upsert Option选项

If the update and replace methods include the com.mongodb.client.model.UpdateOptions parameter that specifies com.mongodb.client.model.UpdateOptions.upsert(true) and no documents match the specified filter, then the operation creates a new document and inserts it. 如果更新和替换方法包括com.mongodb.client.model.UpdateOptions参数,该参数指定com.mongodb.client.model.UpdateOptions.upsert(true),并且没有与指定筛选器匹配的文档,则操作将创建一个新文档并插入它。If there are matching documents, then the operation modifies or replaces the matching document or documents.如果存在匹配文档,则该操作将修改或替换匹配文档。

For details on the new document created, see the individual reference pages for the methods.有关创建的新文档的详细信息,请参阅方法的各个参考页。

Upsert Option选项

If updateOne(), updateMany(), or replaceOne() include upsert : true in the options parameter document and no documents match the specified filter, then the operation creates a new document and inserts it. 如果updateOne()updateMany()replaceOne()options参数文档中包含upsert: true,并且没有与指定筛选器匹配的文档,则该操作将创建一个新文档并将其插入。If there are matching documents, then the operation modifies or replaces the matching document or documents.如果存在匹配文档,则该操作将修改或替换匹配文档。

For details on the new document created, see the individual reference pages for the methods.有关创建的新文档的详细信息,请参阅方法的各个参考页。

Upsert Option选项

If updateOne(), updateMany(), or replaceOne() includes upsert => true and no documents match the specified filter, then the operation creates a new document and inserts it. 如果updateOne()updateMany()replaceOne()包含upsert => true,并且没有与指定筛选器匹配的文档,则该操作将创建一个新文档并将其插入。If there are matching documents, then the operation modifies or replaces the matching document or documents.如果存在匹配文档,则该操作将修改或替换匹配文档。

For details on the new document created, see the individual reference pages for the methods.有关创建的新文档的详细信息,请参阅方法的各个参考页。

Upsert Option选项

If update_one(), update_many(), or replace_one() includes upsert : true and no documents match the specified filter, then the operation creates a new document and inserts it. If there are matching documents, then the operation modifies or replaces the matching document or documents.

For details on the new document created, see the individual reference pages for the methods.有关创建的新文档的详细信息,请参阅方法的各个参考页。

Upsert Option选项

If the update and replace methods include the UpdateOptions parameter that specifies UpdateOptions.upsert(true) and no documents match the specified filter, then the operation creates a new document and inserts it. 如果更新方法和替换方法包含指定UpdateOptions.upsert(true)UpdateOptions参数,并且没有与指定筛选器匹配的文档,则该操作将创建一个新文档并将其插入。If there are matching documents, then the operation modifies or replaces the matching document or documents.如果存在匹配文档,则该操作将修改或替换匹配文档。

For details on the new document created, see the individual reference pages for the methods.有关创建的新文档的详细信息,请参阅方法的各个参考页。

Upsert Option选项

If UpdateOne(), UpdateMany(), or ReplaceOne() includes an UpdateOptions argument instance with the IsUpsert option set to true and no documents match the specified filter, then the operation creates a new document and inserts it. If there are matching documents, then the operation modifies or replaces the matching document or documents.

For details on the new document created, see the individual reference pages for the methods.有关创建的新文档的详细信息,请参阅方法的各个参考页。

Upsert Option选项

If update_one(), update_many(), or replace_one() includes upsert => true and no documents match the specified filter, then the operation creates a new document and inserts it. If there are matching documents, then the operation modifies or replaces the matching document or documents.

For details on the new document created, see the individual reference pages for the methods.有关创建的新文档的详细信息,请参阅方法的各个参考页。

Upsert Option选项

If update_one(), update_many(), or replace_one() includes upsert => true and no documents match the specified filter, then the operation creates a new document and inserts it. If there are matching documents, then the operation modifies or replaces the matching document or documents.

For details on the new document created, see the individual reference pages for the methods.有关创建的新文档的详细信息,请参阅方法的各个参考页。

Upsert Option选项

If updateOne(), updateMany(), or replaceOne() includes upsert => true and no documents match the specified filter, then the operation creates a new document and inserts it. If there are matching documents, then the operation modifies or replaces the matching document or documents.

For details on the new document created, see the individual reference pages for the methods.有关创建的新文档的详细信息,请参阅方法的各个参考页。

Upsert Option选项

If Collection.UpdateOne includes the Upsert option set to true and no documents match the specified filter, then the operation creates a new document and inserts it. If there are matching documents, then the operation modifies or replaces the matching document or documents.

For details on the new document created, see the individual reference pages for the methods.有关创建的新文档的详细信息,请参阅方法的各个参考页。

Write Acknowledgement写确认

With write concerns, you can specify the level of acknowledgement requested from MongoDB for write operations. 对于写操作,您可以指定MongoDB为写操作请求的确认级别。For details, see Write Concern.有关详细信息,请参阅写关注点

See also参阅

  • motor.motor_asyncio.AsyncIOMotorCollection.update_one()
  • motor.motor_asyncio.AsyncIOMotorCollection.update_many()
  • motor.motor_asyncio.AsyncIOMotorCollection.replace_one()
  • Additional Methods