【问题标题】:Querying object arrays with Mongoose使用 Mongoose 查询对象数组
【发布时间】:2021-07-02 18:48:18
【问题描述】:

假设我在猫鼬中有这样一个集合我有这样一个模板

[
  {
    id: 123,
    "arrayvalue": [
      {
        id: 355,
        name: "jhon",
        job: true
      },
      {
        id: 155,
        name: "clarck",
        job: false
      },
      {
        id: 275,
        name: "orie",
        job: true
      },
      
    ]
  }
]

我目前正在使用 nodejs express

我想要做的只是获取值为 true 的对象。

我希望输出是这样的

[
  { id : 123,
    "arrayvalue": [
      {
        "id": 355,
        "job": true,
        "name": "jhon"
      },
      {
        "id": 275,
        "job": true,
        "name": "orie"
      }
    ]
  }
]

找了很多地方都没找到,希望对项目有必要。你可以帮忙

我使用:“猫鼬”:“^5.12.2”

【问题讨论】:

  • 您的查询目前是什么样的?

标签: node.js mongodb mongodb-query aggregation-framework mern


【解决方案1】:

var obj ={
    id : 123,
    arrayvalue : [
     
        {
     id : 355,
    name : "jhon",
    job : true
        },
        {
     id : 155,
    name : "clarck",
    job : false
        },
        {
     id : 275,
    name : "orie",
    job : true
        },
    ]
};
    
    var response = {}; 
    for (var i = 0; i < obj.arrayvalue.length; i++) {
      if (obj.arrayvalue[i].job) {
        response[i] = obj.arrayvalue[i];
      }
    }
    console.log(response);

【讨论】:

    【解决方案2】:

    选项 - 1

    演示 - https://mongoplayground.net/p/z1BwqmFh7Nq

    $unwind

    $push

    $group

    $match

    db.collection.aggregate([
    { $unwind: "$arrayvalue" }, // break into individual documents
    { $match: { "arrayvalue.job": true } }, // match query
    {
      $group: { // join the document back
        _id: "$_id",
        arrayvalue: { $push: "$arrayvalue"}
      }
    }])
    

    选项 - 2

    如果你想在 JS 中做:-

    const data = [{
      id: 123,
      "arrayvalue": [{
          id: 355,
          name: "jhon",
          job: true
        },
        {
          id: 155,
          name: "clarck",
          job: false
        },
        {
          id: 275,
          name: "orie",
          job: true
        },
    
      ]
    }]
    
    const arr = data.map((d) => {
      if (d.arrayvalue) {
        d.arrayvalue = d.arrayvalue.filter(e => e.job === true);
      }
      return d;
    });
    console.log(arr);

    【讨论】:

    猜你喜欢
    • 2014-05-13
    • 2017-08-15
    • 1970-01-01
    • 2020-04-12
    • 2021-01-16
    • 1970-01-01
    • 1970-01-01
    • 2015-05-13
    相关资源
    最近更新 更多