-2

I have the following collection with three documents:

{
   _id: 1
   items: ['1a', '1b', '1c']
},
{
   _id: 2,
   items: ['2a', '2b', '2c']
},
{
   _id: 3,
   items: []
}

I have a query that have to move '1a','1c','2a','2b' elements from their corresponding documents into documents with _id: 3.

I need to get the following result:

{
   _id: 1
   items: ['1b']
},
{
   _id: 2,
   items: ['2c']
},
{
   _id: 3,
   items: ['1a','1c', '2a', '2b']
}

Help me please. What is better solution for resolving my problem?

Paul Mougel
  • 16,728
  • 6
  • 57
  • 64
Erik
  • 14,060
  • 49
  • 132
  • 218
  • Hey guys may you explain why you mark my question with minuses without providing any comments? – Erik Dec 23 '13 at 19:24
  • I don't know why it was downvoted (I did not). But, could you add code to show what you've tried? There's certainly not an automatic way to "move" array elements from one document to another in MongoDB. – WiredPrairie Dec 23 '13 at 19:43

3 Answers3

0

I don't think of any specific operators for move operation. But, I think you could use $push or $addToSet operator for this add operation like below and then remove those items from 1 & 2 documents.

db.testcollection.update({_id:3}, {$addToSet:{ ... }})
sandeep talabathula
  • 3,238
  • 3
  • 29
  • 38
0

firstly, you need to explain why you want to do this. Because what you want to do is just this operator without adding other operation, i wonder the simplest way is do like this:

  1. get the result from db
  2. do the operation what you want
  3. delete the old record and save the modify record into db

although the idea sounds like fool, but it's usful. if you have deep requirement, please give them to us.

allen wang
  • 1,087
  • 2
  • 7
  • 16
  • To to make this safely I need to use something like transactions – Erik Dec 24 '13 at 03:30
  • @Erik You've chosen the wrong database then, MongoDB is transactional to only one document, it is in the documentation – Sammaye Dec 24 '13 at 09:02
  • I may you TokuMX that uses transactions. It's something like InnoDB for MySQL – Erik Dec 24 '13 at 15:25
  • @Erik dude as a person who has done numerous projects in many techs here is a helpful tip, if you are looking for InnoDB for MySQL then use that, drop MongoDB, don't go for TokuMX, go for the tech YOU ARE LOOKING FOR WHICH FILLS YOUR SPECS. – Sammaye Dec 27 '13 at 22:08
  • @Sammaye thanks for the response but I need free definition schema and NoSQL looks better than RDBMS. – Erik Dec 28 '13 at 04:37
-1

use update() with $set operation

db.test1.update({_id:1},{$set:{items:['1b']}})

this will update your array set.

Thanks,

nish71
  • 275
  • 1
  • 7