Home > Blockchain >  Getting an element from subdocument in mongodb
Getting an element from subdocument in mongodb

Time:11-03

I would like to retrieve an element from an array subdocument in MongoDB.

This is my current document

  _id: new ObjectId("6175d614c5a8d65745253aca"),
  fullname: "I'm Admin",
  password: '$2b$10$MNsk4ODki0bdSpliKthdb.0KGvy4xkBxxeadfg2TnQAZf810SQ.3q',
  mobile: '88888888',
  email: '[email protected]',
  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.

CodePudding user response:

you should use $filter in $project like this

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

CodePudding user response:

Try agregate 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" } }
  ])
  • Related