1

I'm trying to get just one field back for all my documents.

I'm new to mongoDB but I can't understand why this isn't working.

var docs = db.collection("articles").find({}, { _id: 0, title:1}).asArray();

I have this query which returns ALL fields, despite putting in the projection of wanting only the title field. The query runs without any errors. Maybe I'm missing something very obvious and need a second pair of eyes to spot it.

Any help is appreciated!

Note: I'm using the mongoDB Atlas' Stitch API.

  • There's nothing wrong with your query so I'm guessing that your observation must be somewhat incorrect... Not sure how this would happen, though. Are you looking at cached output perhaps? – dnickless Sep 28 '18 at 05:13
  • Are you doing this inside of a stitch function? Could you add an example of the data? – haley Sep 28 '18 at 12:26
  • The line above is called after I connected to the database via. A promise call. I'm looking at the results via. Chrome debugger, stepped into every part of the code and nothing is broken. In the end it turned out I needed all fields anyway, but I'm still puzzled as to why the above didn't work – Jon Sharkboy Hill Sep 29 '18 at 12:21

1 Answers1

1

I'm guessing that you're using MongoDB Stitch Browser SDK (currently version 4).

In this case, the collection is an instance of RemoteMongoCollection. Where find() accepts options in RemoteFindOptions format. You can define a projection to limits the fields of the matching documents by defining an object with projection key.

For example:

const client = stitch.Stitch.initializeDefaultAppClient('app-id');
const db = client.getServiceClient(stitch.RemoteMongoClient.factory, 'mongodb-atlas').db('databaseName');

 client.auth.loginWithCredential(new stitch.AnonymousCredential())
       .then(() => {
          db.collection('collectionName')
            .find({}, 
                  {"projection":{"_id":0, "title": 1}}
             )
            .asArray().then(docs => {
              // prints results 
              console.log(docs);
          });
        }).catch(err => {
          // Handle error here
          console.log("Error", err);
 });
Wan B.
  • 18,367
  • 4
  • 54
  • 71
  • Wan is correct. When calling `find` from a Stitch function, the projection is supplied as the second argument. When using the JavaScript SDK, the projection is supplied in the options object which is the second argument to `find`. – Alistair Holt Apr 18 '19 at 15:39