简体   繁体   中英

MongoDB return nested array of objects minus a property within the object (also .then() doesn't work with aggregation)

I'm very new to mongodb and am having difficulty getting to a solution for my use case. For example I have the following document:

{ 
   _id : ObjectId('5rtgwr6gsrtbsr6hsfbsr6bdrfyb'),
   uuid : 'something',
   mainArray : [
       {
           id : 1,
           title: 'A',
           array: ['lots','off','stuff']
       },
       {
           id : 2,
           title: 'B',
           array: ['even','more','stuff']
       }
   ]
}

I'd like to have the following returned:

{ 
   uuid : 'something',
   mainArray : [
       {
           id : 1,
           title: 'A'
       },
       {
           id : 2,
           title: 'B'
       }
   ]
}

I've tried various combinations of using findOne() and aggregate() with $slice and $project . With findOne() , if it worked at all, the who document would be returned. I am unable to test whether attempts at aggregating work because .then((ret)=>{}) promises don't seem to work in node.js for me with it (no issues with findOne ). Calling a function like so

return db.myCollection.aggregate([
    {
       $match: {
          _id:ObjectId(mongo_id)
       }  
    },
    {
        $project : {
            mainArray: {
                id:1,
                title:1
            }
        }
    }
],function(err,res){
    console.log(res)
    return res
})

logs the entire function and not the droids I'm looking for.

This is an alternative solution (to the solution mentioned in the comment by @v1shva)

Instead of using aggregation you can use projection option of .findOne() operation.

db.myCollection.findOne(matchCode, { 
  projection: { _id: false, 'mainArray.array': false } // or { _id: -1, 'mainArray.array': -1 }
})

You're missing toArray() method to obtain the actual result set. Instead you're returning the aggregation cursor object. Try this.

return db.myCollection.aggregate([matchCode,projectCode]).toArray().then(
     data => { 
              console.log(data); 
              return data; 
             }, 
     error => { console.log(error)});

The documnetation on aggregation cursor for MongoDB NodeJS driver can be found here http://mongodb.github.io/node-mongodb-native/3.5/api/AggregationCursor.html#toArray

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