[英]Find documents by array of embedded references in Moongoose (MongoDB)
[英]How to find data within embedded documents array using id mongodb?
我正在使用 mongodb 和 nodejs 在嵌入式文檔中查找數據。 奇怪的事實是查詢在數據庫中有效,但在實際的 nodejs 代碼中無效。
這是我的數據對象:
{
"_id" : ObjectId("5c65866488a1c53464e46dc7"),
"cat_lang" : [
{
"_id" : ObjectId("5c65866488a1c53464e46dc8"),
"en" : "temp",
"it" : "temp"
}
],
"providers" : [
{
"_id" : ObjectId("5c65866488a1c53464e46dc9"),
"provider_name" : "temp0",
"url" : "http://uber.com",
},
{
"_id" : ObjectId("5c65866488a1c53464e46dca"),
"provider_name" : "temp1",
"url" : "http://uber2.com",
}
]}
我在 mongodb shell 中嘗試過這些查詢工作得很好。
db.sideservices.findOne({"_id" : ObjectId("5c65866488a1c53464e46dc7")},{providers: {$elemMatch: {"_id" : ObjectId("5c65866488a1c53464e46dca")}}})
和
db.sideservices.find({"providers._id":ObjectId("5c65866488a1c53464e46dca")},{'providers.$':1})
但是當在 nodejs 中使用相同的函數時,它返回整個對象而不是具有給定 id 的文檔。
this.db.collection('sideservices').find({'providers':{'$elemMatch':{'_id':ObjectId('5c65866488a1c53464e46dca')}}}).toArray((err,res) => {...})
你可以這樣做
this.collection("sideservices").find({
"providers": { "$elemMatch": { "_id": ObjectId("5c65866488a1c53464e46dca") } }
})
.project({
"providers": { "$elemMatch": { "_id": ObjectId("5c65866488a1c53464e46dca") } }
})
.toArray((err,res) => {...})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.