【发布时间】: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 是的,我们必须找出名字