[英]How to update a value if not exist in 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);
});
});
when i run this, it gives 当我运行这个,它给
{
"_id" : ObjectId("582cb4ad5a5a380sadas038dd2f72"),
"sellerId" : "e0a82c3d-079asdas0-49asda97-aasdascdf-0c320e3d7022",
"sellerSku" : "te227"
}
{
"_id" : ObjectId("582cb4ae5a5a380038dd2f73"),
"sellerId" : "e0a82casdsa3d-07asdas90-4997-acdf-0c320e3d7022",
"sellerSku" : "TE231"
}
so it means 所以这意味着
there are books which is readed and listingstatus is not exist (normally listingstatus must be existed) 有些书已被阅读,并且listingstatus不存在(通常必须存在listingstatus)
in reading db, there is booklisting colletion. 在阅读数据库时,有书目目录。 Normally what i need to do is:
通常我需要做的是:
instead of 代替
printjson(bookListing);
i need to update 我需要更新
book.update(listingstatu) in for each but is that possible in javascript? book.update(listingstatu)中的每个,但是在javascript中可能吗?
What aboout this 这是什么
db.getSiblingDB('book').books.update({ "seller": bookListing.sellerId, "sellerSku": bookListing.sellerSku },{ $set: {"listingStatus" : "LISTING_CREATED"}})
instead of 代替
printjson(bookListing)
it wll again call book db. 它会再次调用书数据库。
but to test i made thi instead of 但是为了测试我做了thi而不是
printjson printjson
db.getSiblingDB('book').books.find({ "seller": bookListing.sellerId, "sellerSku": bookListing.sellerSku },{ $set: {"listingStatus" : "LISTING_CREATED"}})
but it doesnot show anyhing 但是它什么也没显示
replace printjson(bookListing)
by this: 替换
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);
So your code becomes : 因此,您的代码变为:
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);
});
});
This will update only matching documents 这只会更新匹配的文档
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.