Mongodb $ in针对数组对象而不是数组对象

编程入门 行业动态 更新时间:2024-10-28 14:30:28
本文介绍了Mongodb $ in针对数组对象而不是数组对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 arr=[{field1:<value1>,field2:<value2}.....]

我想对arr的field1使用$in运算符.我知道我可以创建一个虚拟数组并在虚拟数组中推送field1值.但是,有没有一种方法可以对数组的特定字段使用$in运算符?

I want to use the $in operator against the field1 of arr. I know I could create a dummy array and push the field1 values in the dummy array. But is there a way to use the $in operator against a particular field of an array?

arr数组与集合无关.

我想查询其值在arr的field1中的特定字段上的所有文档-field1应该在运算符$in的右侧

I want to query all the documents on a particular field whose value is in the field1 of arr - field1 should be in the right hand side of operator $in

示例:

arr=[{name:'foo',location:'NY'},{name:'bar',location:'LA'},{name:'foobar',location:'NZ'}] db.collection.find({fieldx:<Here I want some method to obtain all documents whose fieldx values are in the location field of arr>})

输出中应该包含fieldx值出现在arr的location字段中的文档.

The output should contain documents whose fieldx values are present in the location field of arr.

查询的输出应该是

[{... fieldx:'NY', ... }, {... fieldx:'LA', ... }, {... fieldx:'NZ', ... }]

fieldx是我要查询的集合中的字段.它不是我要提供的数组的字段(arr).我想将其匹配到数组的字段(location)-arr我正在提供查询.

fieldx is the field in the collection I am querying on. It is not a field of the array I'm providing(arr). I want to match this to a field(location) of array - arr I'm providing the query.

推荐答案

您需要从输入数组中提取位置"字段,并将其提供给 $in :

You need to extract the "location" fields from your input array and feed them to $in:

var locs = arr.map(function(x) { return x.location } ); db.collection.find({ "fieldx": { "$in": locs } })

在这里作为参考,我将为您重新编写您的问题:

For reference here I'm going to re-write your question for you:

我有一个包含如下文档的集合:

I have a collection that contains documents like this:

{ "fieldx": "NY" } { "fieldx": "LA" } { "fieldx": "SF" }

我所拥有的是一个定义如下的输入数组:

What I have is an input array that is defined like this:

var arr = [ { "name": "foo", "location": "NY"}, { "name": "bar", "location": "LA"}, { "name": "foobar", "location": "NZ"} ];

现在,我想编写一个查询来查找与我要输入的数组中的位置"字段相匹配的所有文档.

Now I want to write a query to find all the documents that match the "location" field in the array I have for input.

我该怎么做?

我尝试过:

db.collection.find({ "fieldx": { "$in": arr } })

但这不匹配.

更多推荐

Mongodb $ in针对数组对象而不是数组对象

本文发布于:2023-11-22 17:18:26,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1618327.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   对象   而不是   Mongodb

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!