我在mongo集合中有一个名为(CustomerInformation)的文档 具有以下结构。
{ "_id" : ObjectId("58f5e68c8205281d68bbb290"),
"_class" : "com.test.dataservices.entity.CustomerInformation",
"organizationInformation" : {
"_id" : "123",
"companyName" : "Test1",
"ibanNumber" : "12345e",
"address" : "estates",
"contractInformation" : {
"duration" : NumberInt(0),
"contractType" : "Gold",
"totalUsers" : NumberInt(0)
},
"users" : [
{
"firstName" : "testuser1",
"emailAddress" : "testuser1@test.com",
"password" : "test1@123",
"userAccessType" : "admin"
},
{
"firstName" : "testuser2",
"emailAddress" : "testuser2@test.com",
"password" : "test2@123",
"userAccessType" : "user"
}
]
}
}
现在我想只检索匹配的emailAddress和Password的用户信息。我正在尝试如下。
Criteria elementMatchCriteria = Criteria.where("organizationInformation.users").
elemMatch(Criteria.where("emailaddress").is("testuser1@test.com").and("password").is(test1@123));
BasicQuery query = new BasicQuery(elementMatchCriteria.getCriteriaObject());
CustomerInformation customer =mongoOperations.findOne(query, CustomerInformation.class);
我正在获取包含所有用户数组的完整文档,我想只检索匹配的用户信息emailAddress和密码。 我的查询或数据模型出了什么问题? 有什么建议?谢谢!
答案 0 :(得分:0)
您可以使用$ unwind聚合查询来实现此目的
db.collection.aggregate([
{
$unwind:"$organizationInformation.users"
},
{
$match:{
"organizationInformation.users.emailAddress":"testuser1@test.com",
"organizationInformation.users.password":"test1@123"
}
},
{
$project:{
"organizationInformation.users":1
}
}
])
结果是:
{
"_id" : ObjectId("58f5e68c8205281d68bbb290"),
"organizationInformation" : {
"users" : {
"firstName" : "testuser1",
"emailAddress" : "testuser1@test.com",
"password" : "test1@123",
"userAccessType" : "admin"
}
}
}
OR
db.collection.aggregate([
{
$unwind:"$organizationInformation.users"
},
{
$match:{
"organizationInformation.users.emailAddress":"testuser1@test.com",
"organizationInformation.users.password":"test1@123"
}
},
{
$project:{
user: "$organizationInformation.users"
}
}
])
结果是:
{
"_id" : ObjectId("58f5e68c8205281d68bbb290"),
"user" : {
"firstName" : "testuser1",
"emailAddress" : "testuser1@test.com",
"password" : "test1@123",
"userAccessType" : "admin"
}
}
答案 1 :(得分:0)
使用位置投影。
Criteria elementMatchCriteria = Criteria.where("organizationInformation.users").elemMatch(Criteria.where("emailAddress").is("testuser1@test.com").and("password").is("test1@123"));
Query query = Query.query(elementMatchCriteria);
query.fields().position("organizationInformation.users", 1);
CustomerInformation customer =mongoOperations.findOne(query, CustomerInformation.class);