1

If this is the structure of my documents...

{
    "_id" : "8vJY4baMbdYkgHian",
    "title" : "Cars",
    "tradename" : [
        {
            "element" : "Audi"
        },
        {
            "element" : "Mercedes"
        }
    ]
}

... and I want to get all tradenames in a result array, this is what I am doing:

Collection.find(
    { tradename: { $elemMatch: { element: { $exists: true } } } }
).forEach(function(res) {
    res.tradename.forEach(function() {
        result.push({ 
            id: res._id, 
            value: res.tradename[0].element, 
            type: 'article' 
        });
    });
});

But it doesn't work.

3
  • Explain "does not work" for us all if you can please. The phrasing of your question title asks for something that MongoDB is just going to do anway without any query conditions. Your query conditions will and should just return everything in your sample document. You could add some explaination as to what is not working like you want and what you expect to see instead. Commented Feb 1, 2016 at 10:38
  • Unfotunatly I can't get the console log as on the online version the script is crashing at this point. I only know this part of code makes the problem. So I try to find out what's wrong with that. Maybe there is a syntax error or any variable gets undefined. If this is the case, I should implement some lines to ignore undefined values... Commented Feb 1, 2016 at 10:43
  • Is this using the node native driver or mongoose? Also the general ask is to please explain the result you expect. The query conditions you are usign don't do anything other than select documents that have the "element" field present in at least one of the array elements. I suspect you wan't something different. So you can edit your question to address the points you have been asked to clarify. Much more informative than comments alone. Commented Feb 1, 2016 at 10:52

1 Answer 1

1

You can use a map function to get an array of all the tradename.element values.

This would look something like:

var result = [];
Collection.find(
    { tradename: { $elemMatch: { element: { $exists: true } } } })
.forEach(function(res) {
    result.push({
        id: res._id,
        value: res.tradename.map(function(tradename) {
            return tradename.element;
        }),
        type: 'article'
    });
});
Sign up to request clarification or add additional context in comments.

Comments

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.