简体   繁体   English

如何在mongoDB中的数组和文档之间进行匹配和查找

[英]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.

相关问题 如何从给定的项目数组中找到其数据与至少一个项目的条件匹配的文档 - mongoDB - How to find documents that their data match a condition on at least one item from a given array of items - mongoDB 如何使用MongoDB查找与自定义字段匹配的文档? - How can I use MongoDB to find documents that match with custom field? 如何使用 id mongodb 在嵌入式文档数组中查找数据? - How to find data within embedded documents array using id mongodb? 如何基于子字符串数组上的字符串匹配查找猫鼬文档 - How to find mongoose documents based on a string match on an array of substrings 在MongoDB中查找具有字符串ID数组的文档 - Find documents with array of string ID's in MongoDB 在Moongoose(MongoDB)中按嵌入式引用数组查找文档 - Find documents by array of embedded references in Moongoose (MongoDB) 有没有办法在 mongoDB 的嵌套数组中查找文档 - Is there a way to find documents in nested array in mongoDB MongoDB Aggregation - 通过另一个对象数组过滤器将文档与对象数组匹配 - MongoDB Aggregation - match documents with array of objects, by another array of objects filter Mongodb 查找匹配多个正则表达式的所有文档 - Mongodb find all documents that match multiple regex's 如何使用 mongoDB 中的值数组更新文档数组? - How to update an array of documents with an array of values in mongoDB?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM