Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongodb subfield select

Hello I have the following db:

a busy cat

My question is how do I "SELECT name FROM posts Where thread=Sloan"

Because I'm trying into RockMongo shell : "db.users.find({"posts.thread":'Sloan'})" but it's return all the collection data

***** Using json-generator.com ********************

[
            '{{repeat(5, 7)}}',
            {
                id: '{{index}}',
                group: '{{surname}}',
                name: '{{firstName}} {{surname}}',

                posts: [
                    '{{repeat(25)}}',
                    {
                        thread:'{{surname}}',
                        sb:[
                            '{{repeat(100)}}',
                            {
                                id: '{{index}}',
                                name: '{{firstName}} {{surname}}'

                            }
                        ]
                    }
                ],

                users:[
                    '{{repeat(25)}}',
                    {
                        name:'{{firstName}}'
                    }]


            }
        ]
like image 450
Xtal Avatar asked Mar 27 '26 01:03

Xtal


1 Answers

To clarify thing a little... if you have a database looking like this:

enter image description here

Then if you do db.users.find({ posts: { $elemMatch: { thread: "Sloan" } } }), you will obtain this (every element posts are included):

enter image description here

And if you do db.users.find({"posts.thread":'Sloan'},{'posts.$':1}), you will obtain this (only the relevant post is included):

enter image description here

(By the way, it's faster to perform... and if you add an index on posts.thread, it will be even faster.)

One last thing, which I think can be misleading here. The db.users.find({ posts: { $elemMatch: { thread: "Sloan" } } }, { name: 1 }) projection will give the element name 'gloria sharpe', but from what I understand from the question, he would prefer to obtain the name which is post.thread.sb.name. That's why he wants to have only the relevant post as an answer and not all the posts of that element.

like image 108
Sebastien C. Avatar answered Mar 29 '26 17:03

Sebastien C.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!