简体   繁体   中英

How to fetch record from multi-di array using mongodb query in node js?

I am new to mongodb where i want to fetch record that matches condition for u_id is equal to particular u_id. I am confusing where/what condition should be applied there for fetching that particular record.

connection.model.find( {'abc.sar.0.u_id': new ObjectID( '56e3e5b6fb33e53f119051f2' )} , function ( err, result ) { });

[
        {
          "_id": "56e15c49908fb5af0238f05c",
          "abc": {
            "sar": [
              {
                "u_id": "56e18c33909aa6f214e17dec",
                "cd": null,
                "_id": "56e18c33909aa6f214e17df0"
              },
              {
                "u_id": "56e18c4a909aa6f214e17df1",
                "cd": null,
                "_id": "56e18c4a909aa6f214e17df5"
              },
              {
                "u_id": "56e18f6a909aa6f214e17df6",
                "cd": null,
                "_id": "56e18f6a909aa6f214e17dfa"
              },
              {
                "u_id": "56e3c477a8b75d720c73e5a7",
                "cd": null,
                "_id": "56e3c477a8b75d720c73e5ab"
              },
              {
                "u_id": "56e3e5b6fb33e53f119051f2",
                "cd": null,
                "_id": "56e3e5b6fb33e53f119051f6"
              },
              {
                "u_id": "56e3e60efb33e53f119051f7",
                "cd": null,
                "_id": "56e3e60efb33e53f119051fb"
              },
              {
                "u_id": "56e3eaedc0e2dba711805f0e",
                "cd": null,
                "_id": "56e3eaedc0e2dba711805f12"
              },
              {
                "u_id": "56e3eb85f81fe30d12507709",
                "cd": null,
                "_id": "56e3eb86f81fe30d1250770d"
              }
            ]
          }
        }
      ]

You want to use $elemMatch .

connection.model.find({
    'abc.sar' : { 
        $elemMatch : {'u_id': new ObjectID( '56e3e5b6fb33e53f119051f2' )}
    }
});

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