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" }
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);
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.