1

我正在尝试删除 Mongodb 中多个文档中数组内的重复对象。我尝试了很多方法但无法修复

文件结构:-

{ 
  "_id" : ObjectId("5a544fe234602415114601d3"), 
  "GstDetails" : [
      {
          "_id" : ObjectId("5e4837374d62f4c95163908e"), 
          "StateId" : "1", 
          "GstIn" : "33ABFFM1655H1ZF", 
          "StateDesc" : "TAMIL NADU", 
          "CityDesc" : "CHENNAI"
      }, 
      {
          "_id" : ObjectId("5e4837484d62f4c9516395e8"), 
          "StateId" : "1", 
          "GstIn" : "33ABFFM1655H1ZF", 
          "StateDesc" : "TAMIL NADU", 
          "CityDesc" : "CHENNAI"
      }
  ]
}

就像我尝试过的更多文件一样:-

  db.Supplier.find({ "GstDetails": { $size: 2 } }).limit(1).forEach(function (doc) {
  var stateId;
  doc.GstDetails.forEach(function (data) {
    if (data.StateId == stateId) {
        pull doc.GstDetails[0];
    } else {
      stateId = data.StateId
    }
    print(JSON.stringify(doc));
  });
  db.Supplier.save(doc)
});
4

1 回答 1

1

检查以下聚合是否满足您的要求:

db.Supplier.aggregate([
  {
    $unwind: "$GstDetails"
  },
  {
    $group: {
      _id: {
        _id: "$_id",
        StateId: "$GstDetails.StateId"
      },
      GstDetails: {
        $push: "$GstDetails"
      }
    }
  },
  {
    $addFields: {
      GstDetails: {
        $slice: [
          "$GstDetails",
          1
        ]
      }
    }
  },
  {
    $unwind: "$GstDetails"
  },
  {
    $group: {
      _id: "$_id._id",
      GstDetails: {
        $push: "$GstDetails"
      }
    }
  }
])

Mongo游乐场

注意:这个read-only查询。如果没问题,你需要在操作符下面添加作为最后阶段(一旦你执行它,它将更新你的文档,没有可用的回滚):

{$out: "Supplier"}
于 2020-02-22T00:25:54.120 回答