查找包含子对象MongoDb和Node.js的特定字段的文档 [英] Find documents that contain certain field for sub-object MongoDb and Node.js
问题描述
我有一个具有以下格式的集合:
I have a collection with the following format:
[
{
firstname: 'Joe',
lastname: 'Blow',
emails: [
{
email: 'test@example.com',
valid: false
},
{
email: 'test2@example.com',
valid: false
}
],
password: 'abc123',
_id: 57017e173915101e0ad5d94a
},
{
firstname: 'Johnny',
lastname: 'Doe',
emails: [
{
email: 'test3@example.com',
valid: false
}
],
password: 'abc123',
_id: 57017e173915101e0ad5d87b
},
]
我试图根据<$ c找到一个用户$ c> emails.email 字段。以下是我到目前为止:
I am trying to find a user based on the emails.email
field. Here is what I have so far:
db.collection('users').aggregate([
{$unwind: "$emails"},
{$group: {_id: "$_id",user_emails: { $push: "$emails.email" } } },
{$match: {'user_emails': { $in: ['test@example.com'] } } }
],
(error, result) => {
console.log(error);
console.log(result);
}
);
当我在mongo shell中运行此命令时,它似乎工作;但是当我在 Node.js
中运行它时,它会输出 null
以查找错误并 []结果
。
When I run this command in the mongo shell it seems to work; however when I run it in Node.js
it prints null
for the error and []
for the result.
我做错了什么?我对 MongoDB
很新,似乎无法解决这个问题。
What am I doing wrong? I am pretty new to MongoDB
and just can't seem to figure this out.
推荐答案
为什么要放松整个电子邮件?当你的收藏增长了大量的记录时,这将是一个非常昂贵的操作。
Why do you want to unwind the entire emails? That will be a very expensive operation when your collection grows with tons of records.
以下查询将返回邮件test2@example.com的用户。我认为那就是你想要的吗?
The below query will return the user with the email test2@example.com. I think thats what you are looking for right?
db.email.find({emails :{$elemMatch:{email:"test2@example.com"}}})
这篇关于查找包含子对象MongoDb和Node.js的特定字段的文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!