Home > Enterprise >  IN MongoDB Query
IN MongoDB Query

Time:01-03

Suppose I have two collections: one with authors and an array of their books and another with orders and array of books:

Authors:

{
    "_id" : 1,
    "name" : "Jane Austen"
    "books" : [ { "book_name": "Pride and prejudice", "pages": 325 }, { "book_name": "Persuassion", "pages": 355 } ];
},
{
    "_id" : 2,
    "name" : "Mark Twain"
    "books" : [ { "book_name": "Tom Swayer", "pages": 500 } ];
}

Order:

{
    "_id" : Order_ID,
    "total : 500
    "books" : [ { "book_name": "Pride and prejudice", "pages": 325 } ];
}

How can I print which orders contained books from "Jane Austen" ?

I tried doing the following:

var austen = db.authors.find({name: "Jane Austen"}, {books: 1, _id: 0});

his would print all the books from Jane Austen as author.

Then I tried doing:

db.order.find( { books{ $in: [austen] } }, { _id: 0 } )

However it does not seem to give me any results back and I am not sure why

CodePudding user response:

You're approach is fine, it's just that you have a types mismatch.

var austen = db.authors.find({name: "Jane Austen"}, {books: 1, _id: 0});

At this point austen is a cursor (or an array of objects depending where you execute this), I recommend you use findOne instead.

var austen = db.authors.findOne({name: "Jane Austen"}, {books: 1, _id: 0});

Now austen is:

{
    "name" : "Jane Austen"
    "books" : [ { "book_name": "Pride and prejudice", "pages": 325 }, { "book_name": "Persuassion", "pages": 355 } ];
}

So now you can do:

db.order.find( { books: { $in: austen.books } }, { _id: 0 } ).toArray();
  • Related