[英]How to match and find between an array and documents in mongoDB
I have an array of IDs like for example 我有一个ID数组,例如
[id1,id2,id3,......] [id1,id2,id3,......]
and i have a collection with documents for example 我有一个文件收集的例子
{ "_id" : ObjectId("1111111111111"), "phoneNumber" : "1234567891", "fid" : "id1", "pid" : "abcd", "activeFlag" : true }, { "_id" : ObjectId("2222222222"), "phoneNumber" : "1234567891", "fid" : "id1", "pid" : "efgh", "activeFlag" : true }, { "_id" : ObjectId("33333333333"), "phoneNumber" : "1234567891", "fid" : "id2", "pid" : "xyz", "activeFlag" : true }, { "_id" : ObjectId("4444444444444"), "phoneNumber" : "1234567891", "fid" : "id3", "pid" : "mnop", "activeFlag" : true }
i want to find the documents with fid which match IDs in my array of IDs , also i want to sort it according to _id and limit is 9. 我想查找具有ID匹配ID数组中的ID的文档,我也想根据_id对其进行排序,限制为9。
if id1 taken then i need all documents which is having fid as id1, like that. 如果使用id1,那么我需要具有fid作为id1的所有文档,就像这样。
This script should do the trick 这个脚本应该可以解决问题
var listId = ["id1", "id2", "id3"];
var cursor = db.collection.find({fid: {$in: listId}}).sort({_id: 1}).limit(9);
// iterate over documents
if (cursor != null && cursor.hasNext()){
while (cursor.hasNext()){
// print documents
print(JSON.stringify(cursor.next()));
}
}
to run it, create a file names script.js
, copy the code above inside it and then run the command 要运行它,请创建一个文件名为script.js
,在其中复制上面的代码,然后运行命令
mongo databaseName < script.js
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.