更新mongodb时执行多个操作:$addToSet、$inc和聚合:$subject

Performing multiple operations when updating mongodb: $addToSet, $inc and aggregations: $subtract

本文关键字:inc subject addToSet mongodb 执行 操作 更新      更新时间:2023-09-26

我正在学习使用mongodb,当我试图在一个更新查询中执行多个操作时,我得到了$addToSet的错误。

代码:

var insertBook = function(db, title, author, price, edition, img, tags, pages, user, callback) {
    db.collection('books').update( 
        { $and:[{ "title":title }, { "edition":edition }] },    
        {
            "title": title,
            "author":author, 
            {$addToSet: { "img": { $each: img }}},  //error(1)
            {$addToSet: { "tags": { $each: tags }}}, //error(2)
            "edition": edition,
            "pages":pages,
            "price":price,  
            "shared":{ $subtract: ["$shared", 0] },
            $inc: {"copies": 1},            
            "availableCopies":{ $subtract: ["$copies","$shared"] },
            {$addToSet: { "ownedBy": user }}, //error(3)
            "registeredOn": { $type: "timestamp"}
        },
        { upsert: true }
    , function(err, result) {
        assert.equal(err, null);
        console.log("Inserted a document into the Books collection.");
        callback(result);
    });
};
MongoClient.connect(url, function(err, db) {
    assert.equal(err, null);
    var title = "Harry Potter and the chamber of secrets";
    var author = "J.K. Rowling";
    var price = 50.00;
    var img = "null";
    var tags = ["Fiction", "Magic"];
    var pages = 450;
    var user = "Amresh Venugopal";
    insertBook(db, title, author, price, edition, img, tags, pages, user, function(){
        db.close();
    });
});

错误:

/home/codewingx/repo/nodeapps/RESTful/model/bookPut.js:33
        {$addToSet: { "img": { $each: img }}},
        ^
SyntaxError: Unexpected token {

在$addToSet的使用过程中,我似乎错过了一些东西。上的示例https://docs.mongodb.org/manual/reference/operator/update/addToSet/#addtoset-修饰符只显示$addToSet操作的使用。

是什么原因导致了这个错误?

您的update语句混合了更新整个文档、特定字段和聚合操作($substract)。不能在更新雄蕊中使用聚合运算符。在没有这些聚合运算符的情况下,您可以使用更新语句,如下所示。

您也不需要$and,因为默认情况是and操作。


  db.collection('books').update(
  { "title":title, "edition":edition },    
  {
    $set: {"title": title,
           "author": author,
           "edition": edition,
           "pages":pages,
           "price":price,
           "registeredOn": new Date()
          },
    $addToSet: { "img": { $each: img }, 
                "tags": { $each: tags }, 
                "ownedBy": user 
               },                       
    $inc: {"copies": 1}
  },
  {upsert: true},
  function (err, res) {
  });