【问题标题】:Find duplicate enteries from collection node js?从集合节点js中查找重复条目?
【发布时间】:2017-12-07 07:01:55
【问题描述】:

我想根据字段“name”找出重复条目,并在结果中获取“name”和“_id”。

我尝试过使用聚合函数,它从数据库中返回所有结果为空:

这是我的代码:

 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,但现在它给了我空值和 6000 的所有结果 json 和空值。

这里是收集中的数据字段:

我的架构是:

  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);

【问题讨论】:

  • 你能发布你的架构吗?
  • @israel.zinc 添加架构
  • 通过重复,我猜是名字,对吗?
  • @israel.zinc 是的,我们必须找出名字

标签: node.js mongodb


【解决方案1】:

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

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

【讨论】:

  • $first 类似于什么??
  • 嗯?我不明白你的问题。顺便说一句,答案与您的原始查询非常相似。
  • 并检查大小写
  • 查询区分大小写。你只是想按名字做,对吧?它能解决你的问题吗?
  • 不,即使我有很多重复条目,它也不会返回任何结果。结果是:[]
猜你喜欢
  • 1970-01-01
  • 2019-08-05
  • 2019-08-03
  • 2019-08-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多