1

我正试图为我的所有文件取回一个字段。

我是 mongoDB 的新手,但我不明白为什么这不起作用。

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

我有这个查询,它返回所有字段,尽管投影只需要标题字段。查询运行没有任何错误。也许我遗漏了一些非常明显的东西,需要第二双眼睛才能发现它。

任何帮助表示赞赏!

注意:我使用的是 mongoDB Atlas 的 Stitch API。

4

1 回答 1

1

我猜您正在使用MongoDB Stitch Browser SDK(当前版本 4)。

在这种情况下,是RemoteMongoCollectioncollection的一个实例。find ()接受RemoteFindOptions格式的选项。您可以通过定义带有键的对象来定义 a 来限制匹配文档的字段。 projectionprojection

例如:

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);
 });
于 2018-10-19T00:20:42.600 回答