如何检查Mongoose中的重复文件?

时间:2017-09-25 02:01:29

标签: node.js mongodb mongoose

以下是我的集合中嵌套文档的示例:

"person" : [
  {
    "title" : "front-end developer",
    "skills" : [
      {
        "name" : "js",
        "project" : "1",
      },
      {
        "name" : "CSS",
        "project" : "5",
      }
    ]
  },
  {
    "title" : "software engineer",
    "skills" : [
      {
        "name" : "Java",
        "project" : "1",
      },
      {
        "name" : "c++",
        "project" : "5",
      }
    ]
  }
]

是否有一种简单的方法可以确定其他文档是否与此对象相同,例如具有相同的键,值和数组索引?目前我检查重复项的方法很长,需要多个嵌套循环。任何帮助将不胜感激。谢谢!

1 个答案:

答案 0 :(得分:1)

如果您想获得一个相同的列表(显然除了_id字段)文档,请按以下步骤操作:

collection.aggregate({
    $project: {
        "_id": 1, // keep the _id field where it is anyway
        "doc": "$$ROOT" // store the entire document in the "doc" field
    }
}, {
    $project: {
        "doc._id": 0 // remove the _id from the stored document because we do not want to compare it
    }
}, {
    $group: {
        "_id": "$doc", // group by the entire document's contents as in "compare the whole document"
        "ids": { $push: "$_id" }, // create an array of all IDs that form this group
        "count": { $sum: 1 } // count the number of documents in this group
    }
}, {
    $match: {
        "count": { $gt: 1 } // only show what's duplicated
    }
})

与聚合框架一样,您可以尝试通过注释掉所有步骤然后逐步再次激活所有步骤来了解每个步骤的确切内容。