简体   繁体   中英

How to use $elemMatch under nested structure mongodb

I have a dataset Like this:

{
    "_id" : ObjectId("5ede21062ce68d29740a861a"),
    "a" : {
        "b" : 0,
        "c" : [ 
            {
                "e" : "5c35f1045643180d9488112f",
                "f" : 1,
                "g" : 2
            }
        ],
        "d" : []
    },
},
{
    "_id" : ObjectId("5ede21062ce68d29740a861b"),
    "a" : {
        "b" : 0,
        "c" : [ 
            {
                "e" : "5c35f1045643180d9488112g",
                "f" : 21,
                "g" : 22
            }
        ],
        "d" : []
    },
}

Now I want to check my 5c35f1045643180d9488112f id exist on e column or not. So if not exist then I will push the objects on c array. If exist then I will increase the counter of g .

I used the $elemMatch approach but I am getting the error ie * Cannot use $elemMatch projection on a nested field.*

I am using Mongoose and node.js

My Code is:

db.Collection.findOne(
 {_id: ObjectId('5ede21062ce68d29740a861a')},
 {'a.c': {$elemMatch: {e: '5c35f1045643180d9488112f'}}}
);
it generates the error -> Cannot use $elemMatch projection on a nested field.

then I tried other approach. In this I am not getting the data but also not getting the result properly. it returns the Blank array.

db.Collection.findOne(
 {_id: ObjectId('5ede21062ce68d29740a861a')},
 {'a': {$elemMatch: {c: {$elemMatch: {e: '5c35f1045643180d9488112f'}}}}}
);
//response id --> {_id: ObjectId('5ede21062ce68d29740a861a'), a: { b: 0, c: [], d: [] }}

Can anyone suggest me where I have done the mistake. Or What is the efficient and suggestable way to achieve this.

Simple way will be first find the data then use javascript to check value exist in array of objects. If exist then write the update query which will increment the counter, if not exist then push the object on array.

But I want to accomplish this through DB Query. Any hellp is really appreciated. Thanks in Advance

Your first approach was almost correct. But there is a syntax error. No need to use separate curly brackets for _id and other conditions.

db.Collection.findOne(
 {_id: ObjectId('5ede21062ce68d29740a861a'),
'a.c': {$elemMatch: {e: '5c35f1045643180d9488112f'}}}
);

Query is:

db.Collection.findOne(
 {
  _id: ObjectId('5ede21062ce68d29740a861a'),
  'a.c.e': '5c35f1045643180d9488112f'
 }
);

So if Id exist then it return the data . If not exist then It return the null .

So if null comes means value not exist so we have to push the object.

If value exist then we have to increment the counter

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM