Ashraf Roomi
Ashraf Roomi

Reputation: 13

How to get the sub document within a nested array in MongoDB?

{
    'userid' : '5e6f2f38e8cfcfaf34ee76a6',
    'c':[
          {'cid':123 ,'flist':['5e6de87050fba047c4c666e1','5e65e475aa1d2a77e1e7d9b3','5e75e5a02dfcda6e321be941']} ,
          {'cid':321 ,'flist':['5e92533b0f93cb0f6d813631','5e946afbfd003483a47d412b','5e6de87050fba047c4c666e1']} , 
          {'cid':431 ,'flist':['5e65e475aa1d2a77e1e7d9b3','5e946afbfd003483a47d412b','5e75e5a02dfcda6e321be941']} 
        ]
}

userid ='5e6f2f38e8cfcfaf34ee76a6'
fid = '5e6de87050fba047c4c666e1'

db.find({'userid':userid ,'c.flist':{'$eq':fid}} , {'c.$.cid':1} )

i am trying to get all cid that the flist contain fid

i tryed this method but i got only first match without {'c.$.cid':1} i got the whole list

Upvotes: 1

Views: 117

Answers (3)

karthikeyan c
karthikeyan c

Reputation: 38

if your intention is to get only cid alone, then below query would work,

db.collection.aggregate([{
    '$match': {
        'userid': '5e6f2f38e8cfcfaf34ee76a6'
    }
},
{
    '$unwind': {
        'path': '$c'
    }
}, {
    '$match': {
        'c.flist': '5e6de87050fba047c4c666e1'
    }
},
{
    '$project': {
        "c.cid": 1,
        "_id": 0
    }
}])

would give you below output

{ "c" : { "cid" : "123" } } 

{ "c" : { "cid" : "321" } }

Upvotes: 2

Abhinandan Kothari
Abhinandan Kothari

Reputation: 303

You can use below query

db.collection.aggregate([ { $match: { userid: "5e6f2f38e8cfcfaf34ee76a6", "c.flist": "5e6de87050fba047c4c666e1" } }, { $addFields: { c: { $filter: { input: { $reduce: { input: "$c", initialValue: [], in: { $concatArrays: [ "$$value", [ { cid: "$$this.cid", flist: { $filter: { input: "$$this.flist", as: "item", cond: { $eq: [ "$$item", "5e6de87050fba047c4c666e1" ] } } } } ] ] } } }, as: "item2", cond: { $gt: [ "$$item2.flist", [] ] } } } } } ]).pretty()

to get the following output

{
    "_id" : ObjectId("5e95ca8801423e0f9af19b4b"),
    "userid" : "5e6f2f38e8cfcfaf34ee76a6",
    "c" : [
        {
            "cid" : 123,
            "flist" : [
                "5e6de87050fba047c4c666e1"
            ]
        },
        {
            "cid" : 321,
            "flist" : [
                "5e6de87050fba047c4c666e1"
            ]
        }
    ]
}

Upvotes: 1

Hitesh Chavan
Hitesh Chavan

Reputation: 86

I think as per your need, you need to change the structure of collection. And as mention in document of MongoDb projection param, The $ operator projects the first matching array element from each document in a collection based on some condition from the query statement you can check that in https://docs.mongodb.com/manual/reference/operator/projection/positional/#project-array-documents.

You need to make cid outside the array I think.

Upvotes: 1

Related Questions