Filter array and document in MongoDB

Viewed 108

Schema

[
    {
        _id:"doc1",
        type:"SR",
        title:"...",
        description:"...",
        author:"5",
        posts:[
            {
                author:"1",
                title:"..."
            },
            {
                author:"2",
                title:"..."
            },
            {
                author:"1",
                title:"..."
            }
        ]
    },
    {
        _id:"doc2",
        type:"SA",
        title:"...",
        description:"...",
        posts:[],
        author:"5"
    }
]

Every Document will have type either SA or SR. If type is SA then posts will be an empty array, otherwise it'll non empty.

Now, i want to get document and array elements based on certain conditions.

  • if type is SA and authorId=5 then return the entire document.
  • if type is SR then return the elements of posts where authorId=1

When type is SA then i would like to get title,description,.. of the document otherwise get the posts by filter.

My Query

Using mongoose

Blog.find({
            $or: [
                {
                    $and: [
                        { type: "SA" },
                        { authorId:"5" }
                    ]
                },
                {
                    "posts.authorId": "1"
                }
            ]
        }, {
            posts: {
                $filter: {
                    input: "$posts",
                    as: "post",
                    cond: {
                        $eq: ["$$post.authorId", "1"]
                    }
                }
            }
        })
            .then(posts => {
                console.log(posts)
            })
            .catch(err => {
                console.log(err);
            })

Returned document

[
    {
        _id:"doc1",
        posts:[ 
            {
                author:"1",
                title:"..."
            },
            {
                author:"1",
                title:"..."
            }
        ]
    },
    {
        _id:"doc2",
        posts:[]
    }
]

How can i include other attribute of doc2?

0 Answers
Related