How to select 2 objects from an array

Asked

Viewed 197 times

3

How can I select only 2 items from a array from inside my Center?

example:

{
    "name": "xpto",
    "age": 11,
    "lista": [{"s": 1}, {"s": 2}, {"s": 3}]
}

I need to get the items you own s with 2 and 3 where the name be it xpto and age 11.

I tried with $and and $lista.$ but I get a mistake from BadValue:

{
    "$and": [
        {"name": "xpto", "age": 11, "lista.s": 2},
        {"name": "xpto", "age": 11, "lista.s": 3}
    ]
},
{
    "lista.$": 2
}

What can happen is 2 or 3 does not exist, so would return only a "list", as I can select the 2 from within the array or return only 1 if the 2 do not exist?

The expected result is:

{
    "name": "xpto",
    "age": 11,
    "lista": [{"s": 2}, {"s": 3}]
}

1 answer

2

To remove objects you don’t have s:2 or s:3, you can give an update:

db.mycollection.update({

    }, {
        $pull: {
            "lista": {
                s: {
                    $nin: [2, 3]
                }
            }
        }
    },
    false,
    true
);

After the update your document will be:

{
    "name": "xpto",
    "age": 11,
    "lista": [{"s": 2}, {"s": 3}]
}

Important

Note that I have not set any conditions in the query. This script changes all documents. If you want, you can filter by name or age in the first parameter of db.collection.update.

Reference in the documentation

$pull

  • The doubt is como selecionar apenas 2 itens de um array, so that you have presented all the items of the array will be returned

  • added the expected result to the question to be clearer

  • @RFL got it! In this case, you can edit this object after executing the query. You want to remove objects from the array that s is different from 2 or 3?

  • did not want to add complexity to the code since the mongo can return the correct values :) You changed your answer and it is now out of scope, I asked how to fetch the items and not how to update my Collection

  • @RFL in the previous answer I told you how to fetch items. What you want to do is manipulate the array lista. What do you mean, exactly, by fetching the items?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.