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

90
Vistas
Output forEach result in the console?

I have this command on the mongo cli, but I am not getting any results:

db.files.find({
    state: 4,
    created : {
            '$gte': ISODate("2017-01-18T00:00:00.000Z"),
            '$lte': ISODate("2017-01-19T00:00:00.000Z")
    }
}).forEach( function (o) {
    db.users.find({"id": ObjectId(o.user)},{"username": 1}).pretty();
});

How do I output the username in the cli?

db.users.find({},{'id':1, 'username':1}).pretty();
{
    "_id" : ObjectId("5489b6abe4b0e66fc6491c85"),
    "username" : "user@domain.tld"
}

db.files.find({ }, {'id': 1, 'user': 1} ).pretty();
{ "_id" : "--M17HJrR1m1svX6GZS-YQ", "user" : "56bfe199fe6cc47d0c2f8781" }
{ "_id" : "--bnG8eJTfiYE08xjDphmQ", "user" : "56c477a9da1173ce065abfbf" }
{ "_id" : "-0G2Q5fQQTCJhqEWjVkQYw", "user" : "57388a9b9ef0e2201245b265" }
over 4 years ago · Santiago Trujillo
2 Respuestas
Responde la pregunta

0

Seeing that user field in the files collection is a string, not ObjectId, you need to create a list of ObjectIds i.e. map the user id strings to an array of ObjectIds that you can query the users collection with.

For example, the following uses the distinct() method with a second query argument on both collections to produce arrays that you can query the references with. The final results will print to console the usernames:

var userIds = db.files.distinct("user", {
    "state": 4,
    "created" : {
        "$gte": ISODate("2017-01-18T00:00:00.000Z"),
        "$lte": ISODate("2017-01-19T00:00:00.000Z")
    }
}).map(function(id) { return ObjectId(id); } );
db.users.distinct("username", {"_id": { "$in": userIds } }).forEach(printjson);

If the user field is an ObjectId, then use the aggregation framework's $lookup operator as follows:

db.files.aggregate([
    {
        "$match": {
            "state": 4,
            "created": {
                "$gte": ISODate("2017-01-18T00:00:00.000Z"),
                "$lte": ISODate("2017-01-19T00:00:00.000Z")
            }
        }
    },
    {
        "$lookup": {
            "from": "users",
            "localField": "user",
            "foreignField": "_id",
            "as": "userList"
        }
    },
    {
        "$project": {
            "user": {
                "$arrayElemAt": ["$userList", 0]
            }
        }
    },
    {
        "$project": {
            "username": "$user.username"
        }
    }
]).map(function(doc) { return doc.username; }).forEach(printjson);
over 4 years ago · Santiago Trujillo Denunciar

0

isn't that should be "_id" instead of "id"

db.files.find({
    state: 4,
    created : {
            '$gte': ISODate("2017-01-18T00:00:00.000Z"),
            '$lte': ISODate("2017-01-19T00:00:00.000Z")
    }
}).forEach( function (o) {
    db.users.find({"_id": ObjectId(o.user)},{"username": 1}).pretty();
});

Also I think you can get all the id and then call in operators too

var userIds = [];
db.files.find({
        state: 4,
        created : {
                '$gte': ISODate("2017-01-18T00:00:00.000Z"),
                '$lte': ISODate("2017-01-19T00:00:00.000Z")
        }
    },{user:1}).forEach( function (o) {
        userIds.push(new ObjectId(o.user));
    });
    db.users.find({"_id": {$in : userIds},{"username": 1}).pretty();

P.S - Chridam approach is more favorable than any of these.

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