'Script that returns _id in MongoDB with JavaScript

I need a javascript code that saves in a variable the _id I'm having trouble getting that _id because it’s inside an array.

I have looked everywhere but I can't find a solution for this.

  {
    "_id": {
      "$oid": "626bacea1847f675e47b2bd8"
    },
    "tipo": "conta",
    "data_abertura": {
      "$date": "2013-02-19T00:00:00Z"
    },
    "observacoes": "Sem observações",
    "iban": "PT50000506515926456299903",
    "saldo": 1456.23,
    "bic": "BBPIPTPL001",
    "tipo_conta": "Conta Ordenado",
    "cartoes": [
      {
        "_id": {
          "$oid": "626bacea1847f675e47b2bd7"
        },
        "num_cartao": 4908509005925727,
        "nome_cartao": "João Correia",
        "validade": {
          "$date": "2025-10-03T00:00:00Z"
        },
        "pin": 5609,
        "cvc": 975,
        "estado": "Ativo",
        "tipo_cartao": "Crédito"
      }
    ],
    "permissoes": {
      "levantamentos": true,
      "depositos": true,
      "pagamentos": true,
      "transferencias": true,
      "creditos": true,
      "acoes": true
    },
    "titulares": [
      {
        "$oid": "626bacea1847f675e47b2bd6"
      }
    ]
  }

I want the cartoes _id

"cartoes": [
      {
        "_id": {
          "$oid": "626bacea1847f675e47b2bd7"
        },

I want something like this:

let conta = db.banco.findOne({"tipo": "conta"});
idConta = conta._id;

console.log("id: " + idConta);//id: 626bacea1847f675e47b2bd8


Solution 1:[1]

Edit:

According to the comments, I understand you want to input num_cartao value and to get an output of the _id of this cartao. You can use an aggregation for this:

const cartao_id = await db.collection.aggregate([
  {
    $match: {cartoes: {$elemMatch: {"num_cartao": 4908509005925727}}}
  },
  {
    $project: {
      cartoes: {
        $filter: {
          input: "$cartoes",
          as: "item",
          cond: {$eq: ["$$item.num_cartao", 4908509005925727]}
        }
      }
    }
  },
  {
    $project: {
      data: {"$arrayElemAt": ["$cartoes", 0]}
    }
  },
  {
    $project: {
      _id: {$toString: "$data._id"}
    }
  }
])

console.log(`cartao_id: ${cartao_id}`);//id: 626bacea1847f675e47b2bd7

That will provide you what you want, as you can see on this playground

You first $match the documents with the right num_cartao, then $filter the right carto from the cartoes array, and then you format it to string.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1