0

Assume I have a collection with documents that look like this:

{
    "_id": ";lkajsdflhkadfhaewifjasdkfjalksdfjs",
    "tree": [
        { "id": "a", "name": "One" },
        { "id": "b", "name": "Two" },
        { "id": "c", "name": "Three" },
        { "id": "d", "name": "Four" }
    ]
}

Now let's say I want to replace the a, b, and c entries in my tree array with e, f, and c entries. Is it possible to do that replace with an update query? If not, is there a way to select the document such that the tree array only contains the c and d entries (or just the d entry)? I want my document to look like this:

{
    "_id": ";lkajsdflhkadfhaewifjasdkfjalksdfjs",
    "tree": [
        { "id": "e", "name": "Five" },
        { "id": "f", "name": "Six" },
        { "id": "c", "name": "Three" },
        { "id": "d", "name": "Four" }
    ]
}

Order of the tree array matters. I'm aware of $splice, but I do not know ahead of time the index of the c entry. Also, the index may vary between documents. Can I do a query inside of $splice that lets me find the index?

3
  • Is your array really large normally? Most of the array operators are designed to work with a single index (or all). Commented Nov 22, 2013 at 16:51
  • The array shouldn't be too large, but it's not technically limited so I can't say it will always be small. Commented Nov 22, 2013 at 17:33
  • The easiest solution is just to load the entire doc and save it with whatever your platform/driver is. Commented Nov 22, 2013 at 17:56

1 Answer 1

1

How about doing a find().forEach?

db.test.find().forEach(function(doc){for (var i = 0; i < doc.tree.length; i++){
  switch(doc.tree[i].id){
    case "a": doc.tree[i] = { "id": "e", "name": "Five" };
    break;
    case "b": doc.tree[i] = { "id": "f", "name": "Six" };
    break;
  }} db.test.save(doc)});

Of course you can put in more specific logic to fit your rules but this will simply replace the a entries with e and b with f.

Sign up to request clarification or add additional context in comments.

1 Comment

I was using a,b,c,d,e,f as examples. It's unknown in practice what they will be.

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.