0

I want to pull only relevant data from mongo.db. Let's say I have a collection "library" which looks like:

[
    {
        "section": "Fantasy",
        "series": {
            "ChroniclesOfNarnia": {
                "books": [
                    {
                        "title": "The Lion, the Witch, and the Wardrobe",
                        "author": "CS Lewis",
                        "bookNum": 1
                    },
                    {
                        "title": "Prince Caspian",
                        "author": "CS Lewis",
                        "bookNum": 2
                    }
                ]
            }
        },
    },
    //a whole bunch of other records
];

I'd like to fetch ONLY the data for the book "Prince Caspian". So:

{
    "title": "Prince Caspian",
    "author": "CS Lewis",
    "bookNum": 2
}

My query looks like so:

db.getCollection('Library').find({"section.series.ChroniclesOfNarnia.books.title": "Prince Caspian"});

This returns the entire record - and not "a whole bunch of other records" and indeed the record contains the data I specified but I dont want all the other data - just the data for that one book. I looked at the mongo docs as well as more docs but I do not see anything that helps. I do see the "projection" option but that seems to deal with fields of objects, not array items...

**NOTE: I am new to mongo and database operations in general... It occurs to me that I may need to make many small collections, or write some service that takes the entire collection and gives me only the bit I need. If so, let me know but I'd favor a less complicated approach

Neil Lunn
  • 148,042
  • 36
  • 346
  • 317
HelloWorld
  • 2,480
  • 3
  • 28
  • 45
  • 2
    It's not the wisest course of action to expect results from a contained array "only". The whole point of actually "embedding" that array of data is because it's meant to be "related" and therefore "often used with" the parent data. If you find that you regularly want "just the parent" and "just the child" then it probably makes more sense in separate collections. It's really just something that you get used to deciding on over time. – Neil Lunn Jun 09 '18 at 05:28
  • If you're still "fuzzy" on the concepts, then [MongoDB relationships: embed or reference?](https://stackoverflow.com/q/5373198/2313887) and [Mongoose populate vs object nesting](https://stackoverflow.com/q/24096546/2313887) outline the "broad strokes" of things to consider. But for matching "embedded" array elements, the [positional `$` operator](https://docs.mongodb.com/manual/reference/operator/projection/positional/) and [`$filter`](https://docs.mongodb.com/manual/reference/operator/aggregation/filter/) are the two main things, depending if you want "one" match or "many". – Neil Lunn Jun 09 '18 at 05:33
  • OK @NeilLunn - appreciate the help. I will look at the docs you reccommend. – HelloWorld Jun 09 '18 at 05:37

0 Answers0