简体   繁体   中英

Mongodb and array inside a document array

I originally developed a schema for a database of events that was like this:

{ events: {  eventid :  
                        {
                         userid : availability
                        }
 }

This worked great when it comes to upsert data (I used the keys to be the data, as you can see). An upsert would simply create a new record, or update the data using dot notation, since all data has to be unique in my case.

This works fine, EXCEPT when I have to query, for example, all the availability of an user through different events - which I couldn't do via query, having to resort to loops to find the data.

So I thought about using the following schema:

{ events : [
            { 
              id : 'event1', 
              usersavailable : [{user : 'a', availability : 'x'},
                                {user : 'a', availability : 'x'}]
                               ]
            }
}

My questions are:

a) Can I keep the first design and still be able to query the number of 'availability' a user has, without iterating on a loop?

b) If not, will I need two operations to upsert unique {user,availability} pairs under the useravailable array of the second schema? There is, if a user (or an event) is not there, will I need more than one operations to insert user/availability pair?

c) Using the second schema, how can I search for all the availabilities of a given user?

Any tips would be greatly welcome! (and if you can use pymongo to show it, even better... ;)

UPDATE:

The idea is that I can update users' availability in case they change their mind. With the first schema, I'd simply do:

db.events.update({},{'events.eventid.userid.availability':'noon'},upsert=True)

On the other hand, I imagine the second schema would be better in order to find all the availability info of an user, though I don't know exactly how to do that. On both schemas it is easy to do that with loops, but I don't know how to query it.

使用聚合,您可以使用addToSet()创建第二种数组形式(如果适用)。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM