Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

284
Visualizações
How can I query the value of an object rather than the key value pair in MongoDB

I've store an array on my user object which holds all of the data

{
   _id: ObjectId(#############)
   fname: 'Bob',
   lname: 'Vargas',
   data: [
     // the data I want
   ]
}

I am using express to get his data like this:

db.users.findOne( { _id: ObjectId(#############) }, { data: 1, _id: 0 } );

but that is giving me an object rather than the array:

{ data: [  /* my data */ ]}

how can I get just the array?

UPDATE

app.get('/user/:id/data', function (req, res, next) {
    db.users.findOne(
        { _id: mongojs.ObjectId(req.params.id) },
        { data: 1, _id: 0 },
        function (err, userData) {
            if (err) {
                res.send(err);
            }
            res.json(userData); 
        }
    );
});
over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

Add projection to query result:

db.users.findOne( { _id: ObjectId(#############) }, {_id:0, data:1} )

Use 0 to exlude field from result (_id is included by default), and 1 to include field in result.

MongoDB returns object per document. But you can manually map objects on client side:

db.users.findOne( { _id: ObjectId(#############) }, {_id:0, data:1} )
        .map(function(d){ return d.data; }))
over 4 years ago · Santiago Trujillo Relatório

0

MongoDB's findOne() will only return an object, not an array; thus the One. Instead you will need to receive it as and object and then get the value.

If you are doing this from mongo shell then there is no way around unless you want to move the data into its own collection. Otherwise you can get the array from the object in your application.

UPDATE:

in your express response, only encode the data value, like this

res.json(userData.data);
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda