Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

insert document in array field

I'm not good at mongodb, so it is hard to manipulate sub documents. What I want to do is implement address book like this:

{
    [[email protected]]: [
        {
            email: '[email protected]',
            createdAt: '0000-00-00',
            updatedAt: '0000-00-00'
        }
    ],
    [[email protected]]: [
        { ... },
        { ... }
    ]
}

I called that collection 'addressbook', and each item is Array type to contain address information like email, image, date of created something like that.

The problem is I don't know how to do it. Looks like I need to use some operators like $addToSet or $push, but I don't get it how to use them correctly. What I tried:

update({
    email: '[email protected]'
}, {
    $push: {
        'address.$email': {
            email: target,
            createdAt: new Date(),
            updatedAt: new Date()
        }
    }
})

One thing I knew was using upsert option to update collection makes new document if it doesn't exists, but still docs are not creating. It will be very appreciate to gimme a hand.

like image 757
modernator Avatar asked Jul 19 '26 00:07

modernator


1 Answers

It looks like structure presented will hold all user data in one document. This could be very tricky in future handling, as bson document have 16MB capacity limit.

If you could consider simpler form of document:

{
   _id:bsonId,       
   email: '[email protected]',
   createdAt: '0000-00-00',
   updatedAt: '0000-00-00',
   name: "unknown"
 }

then updating and maintaining your collection will be a lot easier.

db.addressbook.update({ email: '[email protected]'},{name:"Happy User"})
like image 133
profesor79 Avatar answered Jul 20 '26 13:07

profesor79