从集合节点js中查找重复的enteries?

时间:2017-12-07 07:01:55

标签: node.js mongodb

我想根据字段"找出重复的条目。名字"在结果中,我想要获取"名字"和" _id"。

我尝试过使用聚合函数,它将数据库中的所有结果都返回为null:

这是我的代码:

 ModelRestaurant.aggregate((
    // { "$group": { "_id": "$name", "count": { "$sum": 1 } } },
    // { "$match": { "_id": { "$ne": null }, "count": { "$gt": 1 } } },
    // { "$project": { "name": "$_id", "_id": 0 } }
    { $group: { "_id": "$name", "name": { $first: "$name" }, "count": { $sum: 1 } } },
    { $match: { "count": { $gt: 1 } } },
    { $project: { "name": 1, "_id": 0 } },
    { $group: { "_id": null, "duplicateNames": { $push: "$name" } } },
    { $project: { "_id": 0, "duplicateNames": 1 } }
), function (err, result) {
    if (result) {
        console.log(result)
    }
})

从上面注释的代码中它给了我所有的id但是现在它给了我null值和所有结果json为6000的null值。

这里是集合中的数据字段:    enter image description here

我的架构是:

  var mongoose = require('mongoose');
  var uniqueValidator = require('mongoose-unique-validator');
  var autoIncrement = require('mongoose-auto-increment');

  var ModelRestaurant = new mongoose.Schema({
      name: String,
      ownerName: String, // to be removed by checking code
      ownerID: Number,
      ownerEmail: String, // to be removed by checking code
      city: String,
      zipCode: String,
      image: [String],
      restaurantType: String,
      address: String,
      landmark: String,
      isAddedByCustomer: {
          type: Boolean,
          default: false
      },
      location: {
          lat: String,
          long: String
      }
  },
  {
      timestamps: true
  });
  ModelRestaurant.plugin(autoIncrement.plugin, 'Restaurants');
  ModelRestaurant.plugin(uniqueValidator);
  mongoose.model('Restaurants', ModelRestaurant);

1 个答案:

答案 0 :(得分:0)

以下代码应打印所有重复项:

db.ModelRestaurant.aggregate([
    {$group:{"_id":"$name","name":{$first:"$name"},"count":{$sum:1}}},
    {$match:{"count":{$gt:1}}}
])