skip to Main Content

I want to return the title and _id properties of each element in my trips array of a user’s document. I am attempting to use the aggregate pipeline but its my first time and the docs are overwhelming. It seems like all the examples show how to find a single piece of data. I basically want to return something like this:


[
  {title: "one", _id: 123},
  {title: "two", _id: 456},
  {title: "three", _id: 789},
]

From my document that looks like this:

enter image description here

2

Answers


  1. function ObjArray(array){
        let newArr = [];
        array.foreach(
        (obj) => {
            let newobj = {title: '', id:''}
            newobj.title = obj.title;
            newobj.id = obj.id;
            newArr.append(newobj);
        }
        );
        return newArr;
    }
    
    Login or Signup to reply.
  2. You can use find({}) for getting your expected result. In find query, you need to use a projection stage.

    Here the demo

    Expected query

    db.collection.find({},{_id:1,"trips.title":1,"trips._id":1});
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search