0

I have the following json document:

{
    "Section": {
        "Name": "Section 1",
        "Description": "Section 1 information",
        "Icon": "test.png"
    },
    "Data": [{
        "Name": "Firstname",
        "Desc": "Users first name",
        "Type": "Text"
    }, {
        "Name": "Lastname",
        "Desc": "Users last name",
        "Type": "Text"
    }]
} {
    "Section": {
        "Name": "Section 2",
        "Description": "Section 2 information",
        "Icon": "test.png"
    },
    "Data": [{
        "Name": "Section 2 Item",
        "Desc": "Section 2 Desc",
        "Type": "Text"
    }]
}

I wanted to ask if there is any way to project items based on Data.Name. Like project everything with Data.Name in ['Firstname', 'Section 2 Item'] including the Section object. So the result should be:

{
    "Section": {
        "Name": "Section 1",
        "Description": "Section 1 information",
        "Icon": "test.png"
    },
    "Data": [{
        "Name": "Firstname",
        "Desc": "Users first name",
        "Type": "Text"
    }]
} {
    "Section": {
        "Name": "Section 2",
        "Description": "Section 2 information",
        "Icon": "test.png"
    },
    "Data": [{
        "Name": "Section 2 Item",
        "Desc": "Section 2 Desc",
        "Type": "Text"
    }]
}

Not sure if this is possible.

Thanks in advance.

1 Answer 1

3

You can do this with the $ positional projection operator which identifies the index of the array element matched in the query object:

db.test.find(
    {'Data.Name': {$in: ["Firstname", "Section 2 Item"]}}, 
    {Section: 1, 'Data.$': 1})
Sign up to request clarification or add additional context in comments.

1 Comment

I m sure I tried that before I posted my question. In any case it works exactly as I wanted. Thanks a lot.

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.