gpt4 book ai didi

javascript - 如果 mongodb 中不存在如何更新值

转载 作者:行者123 更新时间:2023-12-03 05:02:38 25 4
gpt4 key购买 nike

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"
}

所以这意味着

有书已读,但listingstatus不存在(通常listingstatus必须存在)

在阅读数据库中,有图书列表收藏。通常我需要做的是:

  • 如果某本书已读且listingstatus不存在,并且该图书sellersku存在于书单集合中,则需要更新listingstatus。

而不是

  printjson(bookListing);

我需要更新

book.update(listingstatu) 在每个中,但这在 javascript 中可能吗?

这个怎么样

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

而不是

printjson(bookListing)

它将再次调用图书数据库。

但是为了测试我做了这个而不是

打印json

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

但它没有显示任何内容

最佳答案

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);

});
});

这将仅更新匹配的文档

关于javascript - 如果 mongodb 中不存在如何更新值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42157421/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com