Adriano Sordi
Adriano Sordi

Reputation: 61

Having problems after getting random document in MongoDB

function randomSpam(){
    MongoClient.connect(uri, function(err, db) {
        if (err) throw err;
        const dbo = db.db("database0");
        dbo.collection("spams").aggregate([{ $sample: { size:1, } }]).toArray(function(err, result) {
            if (err) throw err;
            console.log(result);
            db.close();
             });  
          });
       }

Console output

As you can see above I managed to get a random document, now my question is : How can I access a field of the random document I have got? Thanks. (in this case the field named "link, check console output)

Upvotes: 1

Views: 65

Answers (2)

Or Assayag
Or Assayag

Reputation: 6336

You can try, it should work:

 result[0].link

Upvotes: 0

samyok nepal
samyok nepal

Reputation: 557

result[0].link

is what you want — the 0 refers to the first document, and the link refers to the field.

Upvotes: 2

Related Questions