[英]MongoDB Use $in with array of objects
I have a collection with documents in a MongoDB like this: 我在MongoDB中有一个包含文档的集合,如下所示:
{
"recipe_id": "123",
"recipe_name": "Pizza",
"recipe_author": "Jane Doe"
{
Then, in JavaScript, I have an array of objects like this: 然后,在JavaScript中,我有一个像这样的对象数组:
[{
"author": "John Doe"
}
{
"author": "Jane Doe"
}]
I want to find at least one document where the recipe_author field in MongoDB matches the author field in my JavaScript array of objects, so I can get the author_id. 我想找到至少一个文档,其中MongoDB中的recipe_author字段与我的JavaScript对象数组中的author字段匹配,因此可以获取author_id。
If my authors were in an array, I could check for them all at once like this: 如果我的作者位于一个数组中,我可以像这样一次检查所有对象:
["Jane Doe", "Billy Bob", "Another Author"]
collection.findOne({
'author_name': { $in: authors }
}
But, they are an array of objects. 但是,它们是一组对象。 Is it possible to do something along these lines? 可以按照这些方针做点什么吗?
collection.findOne({ 'author_name': { $in: <each author field in my object> } }
I think iterating author inside $in construct may not be possible , but prior querying required array can be formed . 我认为可能无法在$ in构造中迭代作者,但可以形成事先查询的所需数组。
var author = [{
"author": "John Doe"
}
{
"author": "Jane Doe"
}];
var authorObj = author.map(function(eachObj){
return eachObj.author;
});
collection.findOne({
'author_name': { $in: authorObj }
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.