简体   繁体   中英

How to query all documents in mongodb that do not have a specific id?

I am trying to return all documents that do not have the user's id in the document's followers array.

I am using mongoose with Node.Js but the regular mongodb way should be fine.

EDIT

Adding more info:

Here is an example document:

 {
  __v: 0,
  _id: ObjectId("53333273adf3ede81f0ce23b"),
  title: "fashion",
  date: 1395864179,
  followers: [
    ObjectId("53343ac3abcd1b6016c52c1b")
  ]
}

The query I tried to write but not sure if $nin is correct since the examples on mongodb are the opposite of making sure a field in the document does not equal an array of things, where I want to make sure an array of the document does not include a single element.

Story.find({followers: {$nin: [user]}}, "_id title", {$sort: {date: {{$gte: 30 } }, skip: 5, limit: 100}, function(err, results) {

The model:

var Story = new Schema({
    title: {type: String},  
    followers: [{ type: ObjectId, ref: 'User' }],
    date: {type: Number}
}, {collection: "stories"});

module.exports = mongoose.model('Story', Story);

The call to the server: (note I am converting it from a string to an object Id

GET /stories?userid=53343ac3abcd1b6016c52c1b&count=0 200 201ms - 2b

You can do that with following query;

Story.inventory.find({followers: {$exists: true, $nin: [ "53343ac3abcd1b6016c52c1b" ]}},
                    {$sort: {date: {{$gte: 30 } }, skip: 5, limit: 100, function(err, results) {

});

This query will select all documents in the User collection where the followers field exists and its value does not equal to 53343ac3abcd1b6016c52c1b .

Note: Do not convert id to Object, because mongoose does that for you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM