我在MongoDB中有这个数据:

{
"_id" : ObjectId("5c7e459f875ea5548de25722"),
"Autos" : [
    {
        "_id" : ObjectId("5cad9759e1c3895999adaceb"),
        "deleted" : 1,

    },
    {
        "_id" : ObjectId("5cad9a8be1c3895999adacef"),
        "deleted" : 0,

    },
    {
        "_id" : ObjectId("5cad9aa4e1c3895999adacf0"),
        "deleted" : 0,
    }
]
    }

{
"_id" : ObjectId("5c7e45e9875ea5548de25724"),
"Shoemaking" : [
    {
        "_id" : ObjectId("5cad9770e1c3895999adacec"),
        "deleted" : 1,
    },
    {
        "_id" : ObjectId("5cad9a5de1c3895999adaced"),
        "deleted" : 0,
    },
]

我想基本上select * from table where deleted = 0
显示删除记录等于0的位置。
以下是我迄今为止所做的尝试:
db.rental.find({"Autos.deleted":{$ne: 1}}).pretty()

db.rental.find({"Autos":  {$elemMatch: {deleted: 1 } } } ).pretty()

db.rental.find({"Autos.deleted": 0},{"Autos": {$elemMatch:
{deleted:0}}});

但以上这些都不适合我。我做错什么了?
期望输出:
{
    "_id" : ObjectId("5c7e459f875ea5548de25722"),
    "Autos" : [
        {
            "_id" : ObjectId("5cad9a8be1c3895999adacef"),
            "deleted" : 0,

        },
        {
            "_id" : ObjectId("5cad9aa4e1c3895999adacf0"),
            "deleted" : 0,
        }
    ]
        }

        {
          "_id" : ObjectId("5c7e45e9875ea5548de25724"),
          "Shoemaking" : [
              {
                  "_id" : ObjectId("5cad9a5de1c3895999adaced"),
                  "deleted" : 0,
              },
          ]
}

我希望输出与上面类似,但是到目前为止我尝试的所有查询要么只选择一个数组记录,要么什么都不选择。

最佳答案

db.rental.aggregate([
   {
      $project: {
         Autos: {
            $filter: {
               input: "$Autos",
               as: "auto",
               cond: { $eq:["$$auto.deleted",0] }
            }
         }
      }
   }
])

关于node.js - 如何在MongoDB中的Array字段中投影特定元素?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/55608467/

10-09 20:12