![](/img/trans.png)
[英]how to query mongoDB to get the documents that have the _id value that matches one _id value in an array?
[英]How to query all documents in mongodb that do not have a specific id?
我正在嘗試返回文檔的Followers數組中沒有用戶ID的所有文檔。
我在Node.Js中使用貓鼬,但是常規的mongodb方法應該沒問題。
編輯
添加更多信息:
這是一個示例文件:
{
__v: 0,
_id: ObjectId("53333273adf3ede81f0ce23b"),
title: "fashion",
date: 1395864179,
followers: [
ObjectId("53343ac3abcd1b6016c52c1b")
]
}
我嘗試編寫查詢,但不確定$ nin是否正確,因為mongodb上的示例與確保文檔中的字段不等於事物數組相反,在此我想確保文檔數組確實正確不包含單個元素。
Story.find({followers: {$nin: [user]}}, "_id title", {$sort: {date: {{$gte: 30 } }, skip: 5, limit: 100}, function(err, results) {
該模型:
var Story = new Schema({
title: {type: String},
followers: [{ type: ObjectId, ref: 'User' }],
date: {type: Number}
}, {collection: "stories"});
module.exports = mongoose.model('Story', Story);
對服務器的調用:(請注意,我正在將其從字符串轉換為對象ID
GET /stories?userid=53343ac3abcd1b6016c52c1b&count=0 200 201ms - 2b
您可以通過以下查詢來完成;
Story.inventory.find({followers: {$exists: true, $nin: [ "53343ac3abcd1b6016c52c1b" ]}},
{$sort: {date: {{$gte: 30 } }, skip: 5, limit: 100, function(err, results) {
});
此查詢將選擇“ followers
字段所在的“ User
集合中的所有文檔,並且其值不等於53343ac3abcd1b6016c52c1b
。
注意:請勿將id轉換為Object,因為mongoose會為您完成此操作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.