Proper NoSQL data schema for web photo gallery

后端 未结 3 1258
感动是毒
感动是毒 2021-02-01 19:57

I\'m looking to build an appropriate data structure for NoSQL storage of a photo gallery. In my web application, a photo can be part of 1 or more albums. I have experience with

3条回答
  •  萌比男神i
    2021-02-01 20:18

    Using mongodb lingo, your collections could look like this:

    photos = [
        {
            _id: ObjectId(...),
            title: "...",
            date_uploaded: Date(...),
            albums: [
                ObjectId(...),
                ...
            ]
        },
        ...
    ]
    
    albums = [
        {
            _id: ObjectId(...),
            title: "..."
        }
    ]
    

    Finding the 5 newest photos would be done like this:

    > var latest = db.photos.find({}).sort({date_uploaded:1}).limit(5);
    

    There's no server-side joins in mongo, so you'd have to fetch all the latest albums like this:

    > var latest_albums = latest.find({}, {albums: 1});
    

    Of course, then you have to boil this down into a set.

    It's actually easier if you just embed the album inside the photo documents, since they're small:

    photos = [
        {
            _id: ObjectId(...),
            title: "...",
            date_uploaded: Date(...),
            albums: [
                {name: "family-vacation-2011", title: "My family vacation in 2010"},
                ...
            ]
        },
        ...
    ]
    

    Then querying is the same, but you don't have to join. Finding all photos in an album looks like:

    > db.photos.find({albums:{$elemMatch:{name: "family-vacation-2011"}}});
    

提交回复
热议问题