简体   繁体   English

如何进行 mongo 查询以查找数组包含给定 id 的所有文档?

[英]How to make a mongo query to find all documents where an array contains a given id?

I am not sure what i am doing wrong.我不确定我做错了什么。 I have a User collection which has a field "followingUsers" (array).我有一个用户集合,其中有一个字段“followingUsers”(数组)。 This array contains the id's of other users.该数组包含其他用户的 ID。 When an user gets deleted i want that every other user document no longer has a reference to the deleted user in their followUsers array.当用户被删除时,我希望每个其他用户文档不再在其 followUsers 数组中引用已删除的用户。 I am not experienced with mongo so i decided to make a find query first, but i get back an empty result on each attempt.我对 mongo 没有经验,所以我决定先进行查找查询,但每次尝试都会返回一个空结果。

I wrote the following queries and none of them seem to work:我写了以下查询,但似乎都不起作用:

db.users.find({"followingUsers": "63d0522c655fa263cfe003e7"})
db.users.find({"followingUsers": {"$all": ["63d0522c655fa263cfe003e7"] } } )

In the image you can see the data i expect to get back: Data i expect to get back在图像中你可以看到我希望得到的数据: Data i expect to get back

What am i doing wrong?我究竟做错了什么?

With the help of the user with nickname ray, i found the correct queries:在昵称 ray 的用户的帮助下,我找到了正确的查询:

db.users.find( {'followingUsers': ObjectId("63cff74e3ae933124ee20d05")}  )
db.users.find( {'followingUsers': {"$all":[ ObjectId("63cff74e3ae933124ee20d05") ] }}  )

I was indeed storing ObjectId's inside the array and not just strings.我确实将 ObjectId 存储在数组中,而不仅仅是字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Mongo 查找数组包含给定数组的 x 值的文档 - Mongo find documents where array contains x values of given array Mongo db查询所有文档包含在给定字符串数组中匹配的substring - Mongo db query all documents contains substring matching in a given array of strings 查找引用ID在数组中的所有文档 - Find all documents where ref ID is in array 猫鼬-查找其数组属性包含给定子集的所有文档? - Mongoose - find all documents whose array property contains a given subset? 查找数组中的最大值与查询匹配的所有Mongo文档 - Find all Mongo documents for which the max value in an array matches a query 查询mongo:在集合的所有文档中查找数组的计数 - query mongo : find count of array in all the documents of a collection MongoDB - 仅查找其数组包含查询数组的文档 - MongoDB - Find only documents where their arrays contains the query's array 如何在 mongo db 中编写查询以查找嵌套数组中没有具有给定 id 的元素的元素? - How to write a query in mongo db to find elements in which the nested array does not have an element with the given id? Mongodb 查询:查找具有给定范围内所有数组元素的文档 - Mongodb query: find documents having all elements of array in a given range 查询以找到所有数组属性元素都在数组中的文档 - Query to find documents where all array property elements are in array
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM