2017-07-14 36 views
1

我有一個user_batch集合。它包含以下文件:批量字段名在字段投影中被忽略

[{ 
    _id: ObjectId("594baf96256597ec035df23c"), 
    name: "Batch 1", 
    batchSize: 30, 
    users:[] 
}, 
{ 
    _id: ObjectId("594baf96256597ec035df234"), 
    name: "Batch 2", 
    batchSize: 50, 
    users:[] 
}] 

在查找查詢我想僅投影BATCHSIZE。但是當我從nodejs執行find查詢時,我在查詢結果中得到整個文檔。查詢:

db.collection('user_batch').find({}, {name: 1, batchSize: 1}).toArray((err, result) => { 
    if(err) 
    console.log(err) 
    else 
    console.log(result) 
}) 

如果我只是通過{名稱:1}那麼它將項目_id和名稱。但如果我通過batchSize那麼它將返回整個文檔。

注:而在蒙戈殼牌執行這個查詢

+0

具體哪個節點驅動程序版本你正在用嗎?只是想確認哪些版本受到影響。 –

+0

驅動程序版本 - 2.2.28,mongo - 3.2.14,節點 - 6.9.3 – Monisha

回答

1

你是正確的驅動程序錯誤地將此解釋爲batchSize選項,並忽略投影聲明我不是面臨這個問題。

儘管在現代驅動程序發行版中,正確的方法是實際使用.project()「遊標方法」。這更符合其他語言驅動程序的實現。

db.collection('collection').find() 
     .project({ name: 1, batchSize: 1}) 
     .toArray(); 

作爲一個充分的論證:

const mongodb = require('mongodb'), 
     MongoClient = mongodb.MongoClient; 


(async function() { 

    let db; 

    try { 
    db = await MongoClient.connect('mongodb://localhost/test'); 

    // New form uses .project() as a cursor method 
    let result = await db.collection('collection').find() 
     .project({ name: 1, batchSize: 1}) 
     .toArray(); 

    console.log(JSON.stringify(result,undefined,2)); 

    // Legacy form confuses this as being a legacy "cursor option" 
    let other = await db.collection('collection') 
     .find({},{ name: 1, batchSize: 1 }) 
     .toArray(); 

    console.log(JSON.stringify(other,undefined,2)); 

    } catch(e) { 
    console.error(e) 
    } finally { 
    db.close() 
    } 

})() 

產生輸出:

[ 
    { 
    "_id": "594baf96256597ec035df23c", 
    "name": "Batch 1", 
    "batchSize": 30 
    }, 
    { 
    "_id": "594baf96256597ec035df234", 
    "name": "Batch 2", 
    "batchSize": 50 
    } 
] 
[ 
    { 
    "_id": "594baf96256597ec035df23c", 
    "name": "Batch 1", 
    "batchSize": 30, 
    "users": [] 
    }, 
    { 
    "_id": "594baf96256597ec035df234", 
    "name": "Batch 2", 
    "batchSize": 50, 
    "users": [] 
    } 
] 

當第一輸出形式是糾正一個,使用.project()