addToSet 如果不存在

addToSet if not already present

我有一个架构:

var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var MySchema = new Schema({
    Theme: { type: String },
    Style: { type: String },
    Brand: { type: String },
    UpdatedInfo: [
            {
             _id:false, 
             ThisDate: { type: String },
             NewInfo: {type: String },
             OriginalInfo: {type: String }
            }
    ]    
}, { versionKey: false });

然后我进行更新:

MySchema.update({ Theme: MyTheme }, {
   $addToSet: {
      UpdatedInfo: {
         ThisDate: TheDate,
         NewInfo: TheNewInfo,
         OriginalInfo: TheOriginalInfo
      },
   }
},function (err, result) {
   next(err,result);
});

即使 TheNewInfoTheOriginalInfo 在 [= 的新元素中相同,该查询也会在每个新的 TheDate 数组中添加一个新元素到 UpdatedInfo 数组14=]。 我想要的是添加一个新元素到 UpdatedInfo 只有 如果 NewInfo 确实从 UpdatedInfo 数组元素中的 NewInfo 改变了最近的 ThisDate 日期。

现在 UpdatedInfo 数组如下所示:

"UpdatedInfo" : [ 
    {
        "ThisDate" : "12/15/2015",
        "NewInfo" : "12 500:-",
        "OriginalInfo" : "15 000:-"
    }, 
    {
        "ThisDate" : "12/16/2015",
        "NewInfo" : "12 500:-",
        "OriginalInfo" : "15 000:-"
    }, 
    {
        "ThisDate" : "12/17/2015",
        "NewInfo" : "12 500:-",
        "OriginalInfo" : "15 000:-"
    }
]

并且如果UpdatedInfo从一开始就是空的,它应该向其中添加第一个元素,即:

"UpdatedInfo" : [ 
    {
        "ThisDate" : "12/17/2015",
        "NewInfo" : "12 500:-",
        "OriginalInfo" : "15 000:-"
    }
]

可能吗? 最好的问候

使用$elemMatch检查与TheOriginalInfo匹配的元素是否已过时,同时忽略ThisDate:

MySchema.update(
  {
    UpdatedInfo: {
      $elemMatch: {
        OriginalInfo: TheOriginalInfo,
        NewInfo: {$ne: TheNewInfo}
      }
    }
  },
  {
    $set: {
      "UpdatedInfo.$.NewInfo": TheNewInfo,
      "UpdatedInfo.$.ThisDate": TheDate
    }
  }
);

了解 $ (update)

如果您需要与数组或集合进行高级交互,我建议您将其移出到集合中。

MongoDB 对集合的处理比对数组的处理多得多。