ts mongoose查询特定字符串属性作为字符串数组(而不是对象数组)

vc9ivgsu  于 2022-11-13  发布在  Go
关注(0)|答案(1)|浏览(177)

**我有此mongoose模式,我想以字符串数组的形式查询所有IP属性。**例如[IP,IP,IP,IP] this,而不是[ { ip:IP地址}]

const proxyIpSchema = new Schema<IProxyIp>({
      ip: { 
        type: String,
        required: true,
        //ignore duplicate ip
        unique: true,
      },
      port: {
        type: Number,
        required: false,
        default: null
      },
      reason: {
        type: String,
        required: true,
        default: 'Unknown Detection.'
      }
    },
      {
        timestamps: true,
      }
    );

我不能使用map函数,因为它会消耗后端处理能力。像这样,我希望所有的ips都是一个字符串数组
//从mongo数据库获取所有ip并推送到redis

await ProxyIp.find({}, { ip: 1 }).then(async (docs) => {

  docs.map(async (doc) => {
    await this.RedisClient?.sAdd(redisTable, doc.ip);
  });
  
}).catch((err) => {
});
weylhg0b

weylhg0b1#

这里有一种方法可以将所有"ip"放入一个数组中(在一个对象中)。

db.ProxyIp.aggregate([
  {
    "$group": {
      "_id": null,
      "ips": {
        "$push": "$ip"
      }
    }
  },
  {
    "$unset": "_id"
  }
])

输出示例:

[
  {
    "ips": [
      "102.118.108.76",
      "34.234.240.83",
      "123.76.73.33",
      "134.81.197.85",
      "193.122.45.195",
      "54.25.18.14",
      "185.68.124.193",
      "3.105.130.68",
      "52.72.204.78",
      "117.212.118.167",
      "199.155.140.226",
      "64.194.68.59",
      "57.4.147.57",
      "190.116.4.243",
      "179.111.74.98",
      ...
    ]
  }
[

mongoplayground.net上试试。

相关问题