2015-04-17 140 views
1

我剛剛嘗試過MongoDB & NodeJS並且在使用Nodejs查找特定數組集合時遇到問題。如何使用NodeJS檢索MongoDB中的特定查詢數組集合

這裏的藏品我有:

{ 
    "_id": ObjectId("552aa4da6e25e57ebde7ac6f"), 
    "username": "blablabla", 
    "email": "[email protected]", 
    "password": "Dummy Trip", 
    "itinerary": [ 
    { 
     "_id": ObjectId("552c109adb616795044a919e"), 
     "title": "test-0", 
     "desc": "test-0-desc" 
    }, 
    { 
     "_id": ObjectId("552c10b0db616795044a91a0"), 
     "title": "test-1", 
     "desc": "test-1-desc" 
    }, 
    { 
     "_id": ObjectId("552c1128db616795044a91a1"), 
     "title": "test-2", 
     "desc": "test-2-desc" 
    } 
    ] 
} 

所以我需要找到行程的陣列上,「552c109adb616795044a919e」

在MongoDB中端objecId我使用findOne命令&位置$運營商和它按預期工作,只顯示我搜索的數組。

命令:

db.user.findOne({ "itinerary._id" : ObjectId("552c109adb616795044a919e") }, {"itinerary.$" : 1}) 

結果:

{ 
"_id" : ObjectId("552aa4da6e25e57ebde7ac6f"), 
"itinerary" : [ 
    { 
     "_id" : ObjectId("552c109adb616795044a919e"), 
     "title" : "test-0", 
     "desc" : "test-0-desc" 
    } 
]} 

但是,爲什麼當我試圖實現它的NodeJS,它顯示了所有記錄,而不是特定的陣列我搜索。

這裏是我的NodeJS:

 var userCollection = db.get('user'); 
 
userCollection.findOne({ "itinerary._id" : new ObjectID("552c109adb616795044a919e") }, {"itinerary.$" : 1},function(e,userDocs){ 
 
\t console.log(userDocs); 
 
});

結果的NodeJS(顯示的結果):

{ 
 
    _id: 552aa4da6e25e57ebde7ac6f, 
 
    username: 'blablabla', 
 
    email: '[email protected]', 
 
    password: 'Dummy Trip', 
 
    itinerary: [ 
 
{ 
 
    _id: 552c109adb616795044a919e, 
 
    title: 'test-0', 
 
    desc: 'test-0-desc' 
 
}, 
 
{ 
 
    _id: 552c10b0db616795044a91a0, 
 
    title: 'test-1', 
 
    desc: 'test-1-desc' 
 
}, 
 
{ 
 
    _id: 552c1128db616795044a91a1, 
 
    title: 'test-2', 
 
    desc: 'test-2-desc' 
 
} 
 
    ] 
 
}

我錯過了什麼 這裏 ?

注:

  • 我使用MongoDB的節點本機驅動程序提前

謝謝:)

+0

@墩LucGendreau感謝,但它返回null – Yagi

+2

節點驅動器和外殼有預測不同的語法。你需要指定第二個'options'參數的'fields'字段。查看[findOne的API文檔](http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#findOne)。 – wdberkeley

+0

謝謝@wdberkeley,我已閱讀文檔並實施它,但它仍然返回所有行程內容而不是查詢的行程內容。我只需要找到我搜索的3條路線中的1條。在閱讀了一些資源後,我發現字段選擇只是針對對象,而不是針對數組,而我所擁有的行程是對象數組。嗯你覺得怎麼樣? – Yagi

回答

-1

我假設你itinerary是一個數組。那麼你將不得不使用mongodb中的$elemMatch。更多關於elemMatch的詳細信息。

你可以嘗試類似的東西。

var userCollection = db.get('user'); 
userCollection.findOne({ "itinerary": { $elemMatch: {_id: new ObjectID("552c109adb616795044a919e")}}}, {"itinerary.$" : 1},function(e,userDocs){ 
console.log(userDocs); 
}); 

而且我覺得匹配對象ID,您可以使用mongoose.Types.ObjectId("552c109adb616795044a919e")

+0

hmm ..我試圖按照上面的建議使用$ elemMatch,但它仍然返回所有數組,而不是返回特定的數組 – Yagi

相關問題