1
{
    '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

1

3 Answers 3

2

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" } }

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

Comments

1

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.

Comments

1

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"
            ]
        }
    ]
}

Comments

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.