如果在mongodb中不存在,如何更新值

时间:2017-02-10 10:45:20

标签: javascript mongodb

db.books.find({ "status": "readED", $and: [ { "listingStatus": { $not: { $exists: true } } } ] }).forEach(function(book){

     db.getSiblingDB('reading').bookListing.find({"sellerSku": book.sellerSku, "sellerId":book.seller},{"sellerId": 1, "sellerSku": 1}).forEach(function(bookListing){

     printjson(bookListing);


});

});

当我运行它时,它会给出

 {
    "_id" : ObjectId("582cb4ad5a5a380sadas038dd2f72"),
    "sellerId" : "e0a82c3d-079asdas0-49asda97-aasdascdf-0c320e3d7022",
    "sellerSku" : "te227"
}
{
    "_id" : ObjectId("582cb4ae5a5a380038dd2f73"),
    "sellerId" : "e0a82casdsa3d-07asdas90-4997-acdf-0c320e3d7022",
    "sellerSku" : "TE231"
}

所以这意味着

有书籍被readed并且listingstatus不存在(通常必须存在listingstatus)

在阅读db时,有书单收集。通常我需要做的是:

  • 如果书籍已经出现并且不存在listingstatus,则需要更新列表状态,如果该书籍中的sellersku存在于书籍收藏中。

而不是

  printjson(bookListing);

我需要更新

book.update(listingstatu)中的每一个都可以在javascript中使用吗?

这是什么

db.getSiblingDB('book').books.update({ "seller": bookListing.sellerId, "sellerSku": bookListing.sellerSku },{ $set: {"listingStatus" : "LISTING_CREATED"}})

而不是

printjson(bookListing)

它将再次调用书籍db。

但要测试我做的而不是

printjson

  db.getSiblingDB('book').books.find({ "seller": bookListing.sellerId, "sellerSku": bookListing.sellerSku },{ $set: {"listingStatus" : "LISTING_CREATED"}})

但它没有显示任何影响

1 个答案:

答案 0 :(得分:1)

替换printjson(bookListing)

        // set listingStatus 
        bookListing.listingStatus = "someRandomValue"; 
        // save the document. As a document already exist in the collection 
        // with this _id, it will update it. 
        db.books.save(listingStatus);

所以你的代码变成了:

    db.books.find({ "status": "readED", $and: [ { "listingStatus": { $not: { $exists: true } } } ] }).forEach(function(book){

         db.getSiblingDB('reading').bookListing.find({"sellerSku": book.sellerSku, "sellerId":book.seller},{"sellerId": 1, "sellerSku": 1}).forEach(function(bookListing){

        // set listingStatus 
        bookListing.listingStatus = "someRandomValue"; 
        // save the document. As a document already exist in the collection 
        // with this _id, it will update it. 
        db.books.save(listingStatus);

    });
  });

这将仅更新匹配的文档