如何在MongoDb中更新数组?
这是我的shell脚本我想用这个脚本更新fileInfo一些产品有fileInfo存在而且有些产品有 fileInfo不存在。
所以我的要求是如果fileInfo存在则会更新,如果fileInfo不存在则会创建
我的代码需要进行哪些修改?谢谢你
{
"_id" : ObjectId("56d460721cdb5a4b0a73d4ba"),
"catId" : "56d4558b1cdb5a4b0a73d03b",
"pname" : "ABCName",
"brand" : "ABCBrand",
"actualPrice" : "19",
"offer" : 0,
"shopId" : "56d312a61cdb5a1a2d8045",
"mProId" : "569e04ecd08598371ebe53eb",
"del" : "N",
"createdOn" : "28-Feb-2016 19:29:29 UTC"
}
在每个文件中添加数据
"fileInfo" : [
{
"versionId" : "BHpKOLlsgIRF7JqcBrKLPDFC5OgUAUEp",
"fileKey" : "productFile/abc.jpg"
}
],
这是我的shell脚本代码
var product = currentDb.getCollection("product");
var shop_id = "56d312a61cdb5a1a2d8045";
var mproductData = mproduct.find();
var productData = product.find({shopId:shop_id});
var productData1 = product.find({shopId:shop_id}).count();
var count=0;
var mcount=0;
for(var i=0;i<mproductData.length();i++)
{
mcount++
for(var j=0;j<productData.length();j++)
{
if(mproductData[i]._id==productData[j].mProId)
{
count++;
var mpro_id = mproductData[i]._id;
var mfile_version = mproductData[i].fileInfo[0].versionId;
var mfile_key = mproductData[i].fileInfo[0].fileKey;
print(mpro_id);
print(mfile_info);
print(mfile_key);
if(mproductData[i]._id==productData[j].mProId)
{
count++;
var mpro_id = mproductData[i]._id;
var mfile_version = mproductData[i].fileInfo[0].versionId;
var mfile_key = mproductData[i].fileInfo[0].fileKey;
print(mpro_id);
print(mfile_info);
print(mfile_key);
product.update({"mProId":''+mpro_id+''},{"$set": {"fileInfo" : [{"versionId" : ''+mfile_info+'',"fileKey" : ''+mfile_key+''}]}};
}
}
}
答案 0 :(得分:0)
尝试
db.collection.update({},{$set: {"fileInfo" : [
{
"versionId" : "BHpKOLlsgIRF7JqcBrKLPDFC5OgUAUEp",
"fileKey" : "productFile/abc.jpg"
}
]}},{multi:true})
如果它不存在,这将创建fileInfo
属性,否则只需更新它