3

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.

7
  • so u want to push data into mongoDB right? Commented Jun 4, 2016 at 8:07
  • You might have some trouble nesting the documents so deeply like that. Mongo has had trouble updating deeply nested documents. Commented Jun 4, 2016 at 8:08
  • You're on the right track, you would use $push or $pull to add or remove content to or from an existing document. Commented Jun 4, 2016 at 8:10
  • oh, thanks. i forgot to tell this is mongodb. Commented Jun 4, 2016 at 8:32
  • 1
    Please show valid BSON document not pseudo-document. Commented Jun 4, 2016 at 8:41

1 Answer 1

1

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"})
Sign up to request clarification or add additional context in comments.

1 Comment

oh... i forgot to limit of each document. i should try it. thanks :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.