简体   繁体   English

从mongodb的子文档中获取元素

[英]Getting an element from subdocument in mongodb

I would like to retrieve an element from an array subdocument in MongoDB.我想从 MongoDB 中的数组子文档中检索一个元素。

This is my current document这是我目前的文件

  _id: new ObjectId("6175d614c5a8d65745253aca"),
  fullname: "I'm Admin",
  password: '$2b$10$MNsk4ODki0bdSpliKthdb.0KGvy4xkBxxeadfg2TnQAZf810SQ.3q',
  mobile: '88888888',
  email: 'admin@gmail.com',
  accountBalance: 979000,
  __v: 0,
  tradeTransactions: [
    {
      transactionId: 2021-11-02T00:55:52.268Z,
      itemName: 'banana',
      purchasePrice: 1,
      purchaseAmount: 8000
    },
    {
      transactionId: 123,
      itemName: 'apple',
      purchasePrice: 2,
      purchaseAmount: 5000
    }
  ]
}

I want to be able to get我希望能够得到

    {
      transactionId: 2021-11-02T00:55:52.268Z,
      itemName: 'banana',
      purchasePrice: 1,
      purchaseAmount: 8000
    }

I tried to use but it doesn't give me the result that I wanted.我尝试使用,但它没有给我想要的结果。

const test = user.findOne({"tradeTransactions.transactionId" : "2021-11-02T00:55:52.268Z"}, {"tradeTransactions.$" : 1, "transactionId" : 0})

I also tried but it was giving me a bunch of undefined我也尝试过,但它给了我一堆未定义的

user.find({
            "tradeTransactions": {
              $elemMatch: {"transactionId": "123"}
            }
          },
          {"tradeTransactions.$": 1})   

Could I please get some guidance?我能得到一些指导吗?

Thank you very much.非常感谢。

Try agregate https://mongoplayground.net/p/dDUJO944DIP尝试聚合https://mongoplayground.net/p/dDUJO944DIP

user.collection.aggregate([
  { $match: { _id: ObjectId("6175d614c5a8d65745253aca") } },
  { $unwind: "$tradeTransactions" },
  { $match: { "tradeTransactions.transactionId": "2021-11-02T00:55:52.268Z" } },
  { $replaceRoot: { newRoot: "$tradeTransactions" } }
  ])

you should use $filter in $project like this你应该像这样在$project使用$filter

db.collection.aggregate([
  {
    "$project": {
      _id: 0,
      tradeTransactions: {
        "$filter": {
          "input": "$tradeTransactions",
          "as": "t",
          "cond": {
            $eq: [
              "$$t.transactionId",
              "2021-11-02T00:55:52.268Z"
            ]
          }
        }
      }
    }
  }
])

https://mongoplayground.net/p/bUACdhesUI8 https://mongoplayground.net/p/bUACdhesUI8

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM