Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

277
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda