【问题标题】:Add and update subdocument in mongoDB and node js (without mongoose)在 mongoDB 和 node js 中添加和更新子文档(没有 mongoose)
【发布时间】:2017-04-07 03:49:00
【问题描述】:

我对 node js 和 mongoDB 还很陌生,我需要在 mongodb 集合上添加或更新子文档,如下所示:

{
    "_id": "58286e49769e3729e895d239",
    "id": "2",
    "title": "Session Title",
    "sessiondate": "2016-02-11T21:00:00.000Z",
    "startTime": "14:30",
    "endTime": "16:30",
    "breakStartTime": "16:30",
    "breakEndTime": "18:00",
    "talks": [
        {
            "id": "3",
            "title": "Android",
            "speaker": {
                "id": "1",
                "name": "john doe",
                "about": "about the speaker",
                "photo": "https://pbs.twimg.com/profile_images/566353055788978177/dUy_ueY2.jpeg"
            }
        }
    ]
}

我找到的所有解决方案都是使用 mongoose,在这个特定项目中我们决定不使用 mongoose,有什么想法吗?

【问题讨论】:

    标签: javascript json node.js mongodb


    【解决方案1】:

    看看Node.JS MongoDB driver

    基本示例

    var Db = require('mongodb').Db,
        MongoClient = require('mongodb').MongoClient,
        Server = require('mongodb').Server,
        ReplSetServers = require('mongodb').ReplSetServers,
        ObjectID = require('mongodb').ObjectID,
        Binary = require('mongodb').Binary,
        GridStore = require('mongodb').GridStore,
        Grid = require('mongodb').Grid,
        Code = require('mongodb').Code,
        BSON = require('mongodb').pure().BSON,
        assert = require('assert');
    
      // Set up the connection to the local db
      var mongoclient = new MongoClient(new Server("localhost", 27017), {native_parser: true});
    
      // Open the connection to the server
      mongoclient.open(function(err, mongoclient) {
    
        // Get the first db and do an update document on it
        var db = mongoclient.db("integration_tests");
        db.collection('mongoclient_test').update({a:1}, {b:1}, {upsert:true}, function(err, result) {
          assert.equal(null, err);
          assert.equal(1, result);
    
          // Get another db and do an update document on it
          var db2 = mongoclient.db("integration_tests2");
          db2.collection('mongoclient_test').update({a:1}, {b:1}, {upsert:true}, function(err, result) {
            assert.equal(null, err);
            assert.equal(1, result);
    
            // Close the connection
            mongoclient.close();
          });
        });
      });
    

    【讨论】:

    【解决方案2】:

    要在嵌入文档中添加或更新新的talk,您可以使用任何原子update operators,具体取决于集合中的文档数量 你想更新。对于单个原子更新,请使用 updateOne() 方法,如下例所示:

    1.添加新的子文档

    // Example of adding a subdocument to an existing document.
    
    var MongoClient = require('mongodb').MongoClient,
        ObjectId = require('mongodb').ObjectId;
    
    MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
    
        // Get a collection
        var collection = db.collection('mycollection');
    
        // The new talk document to be added 
        var doc = {
            "id": "4",
            "title": "PyData",
            "speaker": {
                "id": "7",
                "name": "alice bob",
                "about": "about the speaker",
                "photo": "https://pbs.twimg.com/dUy_ueY2.jpeg"
            }
        };
    
        // Update the document with an atomic operator
        collection.updateOne(
            { "_id": ObjectId("58286e49769e3729e895d239") },
            { "$push": { "talks": doc } },
            function(err, result){
                console.log(result);
                db.close();
            }
        )
    
    });
    

    在上面,您使用 $push 运算符将指定文档附加到嵌入文档数组(talks 字段)。


    2。更新现有子文档

    // Example of updating an existing subdocument.
    
    var MongoClient = require('mongodb').MongoClient,
        ObjectId = require('mongodb').ObjectId;
    
    MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
    
        // Get a collection
        var collection = db.collection('mycollection');
    
        // Update the document with an atomic operator
        collection.updateOne(
            { 
                "_id": ObjectId("58286e49769e3729e895d239"),
                "talk.id": "3"
            },
            { "$set": { 
                "talks.$.title": "Android version 7.0",
                "talks.$.speaker.name": "foo bar"
            } },
            function(err, result){
                console.log(result);
                db.close();
            }
        )
    
    });
    

    对于现有的文档更新,您可以在更新操作中应用 $set 运算符和 $ positional operator 来更改嵌入的文档字段。 $ positional operator 将识别数组中要更新的正确元素,而无需显式指定数组中元素的位置。为此,数组字段必须作为查询文档的一部分出现,因此查询

    { 
        "_id": ObjectId("58286e49769e3729e895d239"),
        "talk.id": "3" // <-- array field is part of the query
    }
    

    【讨论】:

    • 很好的答案!非常感谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-04-05
    • 2016-01-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-18
    • 1970-01-01
    相关资源
    最近更新 更多