Mongoose独特的选择但整个对象

时间:2018-04-02 09:36:44

标签: node.js mongodb mongoose

在Node.js中使用Mongoose。我在MongoDB中有这个模型结构:

{
   "_id":"5ac17dc27707e91ed00cea7d",
   "appid":123,
   "name":"Stellaris",
   "code":"xxxxxxxxxxx"
}

我需要选择所有项目但是当有更多相同appid的项目时,只选择一个或每个appid。不同的返回只是一个字段的数组。如何选择整个对象而不是具有相同appid的项目只有一次?

3 个答案:

答案 0 :(得分:2)

试试这个

db.getCollection('Collection').aggregate([{
    $group: {
        _id: '$appid',
        "docs": {
            $first: {
                "name": "$name",
                "code": "$code"
            }
        }
    }
}])

如果您不想要文档字段。

db.getCollection('Collection').aggregate([{
    $group: {
        _id: '$appid',
        "name": {
            $first: "$name"
        },
        "code": {
            $first: "$code"
        }
    }
}])

答案 1 :(得分:0)

按照以下步骤操作: -

UserSchema = new Schema({
  code: {
   type: String,
   required: 'code id cannot be blank',
  },
  name: {
  type: String,
  required: 'Name  cannot be blank',
  },
 appId: {
  type: String,
   unique: true,  
   required: 'app id cannot be blank',
 },

});

mongoose.model('users', UserSchema);

要创建唯一的字段,请执行unique : true

答案 2 :(得分:0)

在我看来,在mongo db中没有重复的对象存储。因为它生成随机id。如果你想获得内部对象,那么你可以使用不同的https://docs.mongodb.com/manual/reference/method/db.collection.distinct/

否则您可以执行以下步骤。

  1. 从集合中获取所有数据作为数组。
  2. 使用lodash查找duplicat。 https://lodash.com/docs/4.17.5#uniq
  3. 您需要在nodejs项目中安装它

    npm i --save lodash

  4. 然后使用

    _.uniq(Your Array);
    

    并使用

    <h4 class="modal-title pull-left" id="successmodalLabel">This is a title</h4>