user39063
user39063

Reputation: 325

MongoDB List of Subdocuments

I have a question about Subdocuments. Lets say I have a user Database like this:

db.users.insertMany([
{
    username: "test",
    projectA: [
        {
            tags: ['1234', '23454']
        }

    ]
},

{
    username: "test2",
    projectA: [
        {
            tags: ['1dfdfsdf', '234dfdfdf54']
        }

    ]
},
]);

Below the User Document I have Subdocuments with the Projects. Let's say, that one of the Project is called "ProjectA". And under this document I store the data of the Project, in my example some tags.

I have no use for the whole User-Model, because it can be a lot of data. What I want is a list with all tags in the Database under the User and projectA.

I use NodeJS with mongoose to get the data. How can I do it?

Upvotes: 1

Views: 43

Answers (2)

mickl
mickl

Reputation: 49985

You can use $match for filtering and $project for getting the subset of the data:

db.collection.aggregate([
    { $match: { username: "test" } },
    { $project: {"projectA.tags": 1} }
])

Mongo Playground

Upvotes: 1

Algo7
Algo7

Reputation: 2166

MongoDB and Mongoose have no built-in functionality to exactly what you want. After querying the database, you will have to write custom code to loop through the array of documents being returned.

Something like this:


db.collection.find({})
.lean()
.sort({data:1})
.limit(10)
.then(data=>{

//Process your data here using custom codes

for (let index = 0; index < data.length; index++) {
    const element = array[index].ProjectA.tags;
    console.log(element);
    }
})

.catch(err=>console.log(err));

Here I assume that the project filed is always going to be called ProjectA for and the tag filed will always be called tags.

Upvotes: 0

Related Questions