0

I have a users collection whose schema is as follow :

var userSchema = new mongoose.Schema({
  id : Number,
  tags                  : 
    [
      {
        tag_name : String,
        tag_url  : String, 
        posts    : 
          [
            {
                post_id: String
            }
          ]
      }                  
    ]
});

What I would like to do is retrieving only tag_name whose post_id value is in the posts array. So, I tried query as follow

db.users.find({'tags.posts.post_id':'000000'}, {'tags.tag_name':1})

Unfortunatelly, I got all tag_name although post_id is not in posts array.

Can you help me to write query for this?

Edit =================================================================

Let's say I have data as follow :

tags
[
  { 
    tag_name: 'java',
    posts   : [{post_id:'000000'}, {post_id:'111111'}
  },
  { 
    tag_name: 'ruby',
    posts   : [{post_id:'000000'}, {post_id:'111111'}
  },
  { 
    tag_name: 'php',
    posts   : [{post_id:'111111'}
  },
]

I want to have tag element by post_id, if I search by post_id is '000000' I want to get only tag elements whose tag_name is 'java' and 'ruby' not the last tag element, is it possible?

0

1 Answer 1

1

$ in tags.$.tag_name should help:

db.users.find({'tags.posts.post_id':'000000'}, {'tags.$.tag_name':1})

EDIT: ok, I read your update. In this case I see a solution in aggregation framework. We can try build pipeline like this:

db.col.aggregate(
    {$match: {'tags.posts.post_id':'000000'}}, 
    {$unwind: '$tags'}, 
    {$match: {'tags.posts.post_id':'000000'}}, 
    {$group: {_id:'$_id', tags: {$push: '$tags'}}}
)

result will be:

{
        "_id" : ObjectId("5209f5e4ef21a864f6f6ed54"),
        "tags" : [
            {
                "tag_name" : "java",
                "posts" : [
                    { "post_id" : "000000" },
                    { "post_id" : "111111" }
                ]
            },
            {
                "tag_name" : "ruby",
                "posts" : [
                    { "post_id" : "000000" },
                    { "post_id" : "111111" }
                ]
            }
        ]
}

as you might see I did $match twice. It was for performance purposes. By first matching we reduce set of documents that contain post_id:000000 from a collection. Second match filters tags

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for your answer, evilive. btw, it seems to retrieve only one tag element from tags array. If '000000' is in number of tag elements in tags array, I want to get all those tag elements.

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.