Mary Voulieri
Mary Voulieri

Reputation: 23

MongoDB: User defined variable into query

I'm new to MongoDB shell and I need some help !

I have 2 collections: movies and comments. I want to store a value from the second collection and use it to find something in the first.

This is what I have tried :

var result = db.comments.findOne({name: "Arya Stark"})
var movieId = JSON.stringify(result.movie_id.valueOf())
db.movies.findOne({_id: ObjectId($$movieId)})

The above prints that $$movieId is not defined. I have also tried :

db.movies.find({_id: {$toObjectId: movieId}})

and even though my version is 4.2.3, it prints:

unknown operator: $toObjectId.

I have tried everything, I don't know what else to do.

EDIT :

Here's the printed result :

{
        "_id" : ObjectId("5a9427648b0beebeb6957d48"),
        "name" : "Arya Stark",
        "email" : "[email protected]",
        "movie_id" : ObjectId("573a1392f29313caabcd9906"),
        "text" : "Laborum incidunt asperiores accusamus facilis vitae ut quidem. Praesentium provident explicabo odit dolores unde amet architecto. Iure id vero temporibus assumenda eum quia.",
        "date" : ISODate("1978-07-29T23:20:45Z")
}

Basically I want to take the movie_id from the collection comments and use it in the collection movies to search from which movie it is.

Upvotes: 2

Views: 1558

Answers (1)

whoami - fakeFaceTrueSoul
whoami - fakeFaceTrueSoul

Reputation: 17915

You don't need to do two database calls, instead use $lookup for JOINS, try to execute below query in shell :

db.comments.aggregate([{ $match: { name: "Arya Stark" } }, {
    $lookup:
    {
        from: "movies",
        localField: "movie_id",
        foreignField: "_id",
        as: "movie"
    }
}, { $unwind: '$movie' }])

Your two issues are :

  1. when you use $$ in your query that respective variable has to be declared locally in query itself.
  2. $toObjectId is an aggregation operator, which can't be used like that in .find().

Upvotes: 1

Related Questions