我在集合(表)中有一个非常简单的文档(行)结构 - 名为
user_records
,如下所示:
[
{
_id: new ObjectId("652edd74bdb84c9944d280d6"),
customer_id: 1001,
first_name: 'Test',
last_name: 'User',
username: 'Tuser',
password: 'Testuser',
registration_date: 2023-10-17T13:54:54.000Z
}
]
我想运行一个仅返回
customer ID
、first name
、last name
和 username
的查询,其中 username
= username
。但是,我尝试过的所有查询都只返回完整的文档(行)。
我的第一次尝试是这个,很大程度上受到 MongoDB Compass AI 的启发:
// Define query parameters
const filter = { 'username': username };
const projections = {
'_id': 0,
'customer_id': 1,
'first_name': 1,
'last_name': 1,
'username': 1,
'password': 0,
'registration_date': 0
};
const customersCollection = client.db('customer_data').collection('user_records');
const customer = await customersCollection.find(filter, projections).toArray();
在尝试使其正常工作时,我还尝试了一些修改:
''
。projections
作为对象传递给 .find
。就像.find(filter, { projections })
。findOne
代替。以上均无效。
我的第二次尝试更加复杂。我没有定义一个
projections
对象,而是这样做了:
const customersCollection = client.db('customer_data').collection('user_records');
const customer = await customersCollection.aggregate([
{ $match: filter },
{
$project: {
'_id': 0,
'customer_id': 1,
'first_name': 1,
'last_name': 1,
'username': 1,
'password': 0,
'registration_date': 0
}
}
]).toArray();
这没有返回任何东西。
在这一切中,我只是想让
customer
握住这个:
[
{
customer_id: 1001,
first_name: 'Test',
last_name: 'User',
username: 'Tuser',
}
]
我几天前才开始使用 MongoDB,之前是 MySQL;任何形式的帮助将不胜感激。
总的来说,我认为我们需要更多调试细节。
假设您第一次尝试中的
username
变量设置为字符串 'Tuser'
,它甚至不会运行,因为它混合了“包含”和“排除”投影。您可以在这个游乐场示例中看到错误。
我们不知道您第二次尝试中的
filter
变量是什么。如果我假设它是类似的{ username: 'Tuser' }
,那么由于投影格式错误,它也会失败并出现相同的错误。您可以在这个游乐场示例中看到这一点。
您确定您共享的(重新编译的?)代码/查询就是发送到数据库的内容吗?
_id
场。这需要从投影中删除最后两行,例如:
db.collection.find({
"username": "Tuser"
},
{
"_id": 0,
"customer_id": 1,
"first_name": 1,
"last_name": 1,
"username": 1
})
当您对包含这两个文档的集合运行该查询时:
[
{
_id: ObjectId("652edd74bdb84c9944d280d6"),
customer_id: 1001,
first_name: "Test",
last_name: "User",
username: "Tuser",
password: "Testuser",
registration_date: new Date("2023-10-17T13:54:54.000Z")
},
{
username: "other"
}
]
输出为:
[
{
"customer_id": 1001,
"first_name": "Test",
"last_name": "User",
"username": "Tuser"
}
]
这似乎就是您所要求的。在这个游乐场示例中了解它是如何工作的。