Mongodb Spring数据Mongo DB查询嵌入式阵列
我在mongo集合中有一个名为(CustomerInformation)的文档 具有以下结构Mongodb Spring数据Mongo DB查询嵌入式阵列,mongodb,spring-data,spring-mongodb,Mongodb,Spring Data,Spring Mongodb,我在mongo集合中有一个名为(CustomerInformation)的文档 具有以下结构 { "_id" : ObjectId("58f5e68c8205281d68bbb290"), "_class" : "com.test.dataservices.entity.CustomerInformation", "organizationInformation" : { "_id" :
{ "_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"
}
]
}
}
现在,我只想检索具有匹配电子邮件地址和密码的用户信息。我正在做如下的尝试
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);
我正在获取包含所有用户数组的完整文档,我只想检索匹配的用户信息电子邮件地址和密码。
我的查询或数据模型有什么问题?
有什么建议吗?谢谢大家! 您可以将聚合查询与$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"
}
}
}
{
"_id" : ObjectId("58f5e68c8205281d68bbb290"),
"user" : {
"firstName" : "testuser1",
"emailAddress" : "testuser1@test.com",
"password" : "test1@123",
"userAccessType" : "admin"
}
}
或
结果是:
{
"_id" : ObjectId("58f5e68c8205281d68bbb290"),
"organizationInformation" : {
"users" : {
"firstName" : "testuser1",
"emailAddress" : "testuser1@test.com",
"password" : "test1@123",
"userAccessType" : "admin"
}
}
}
{
"_id" : ObjectId("58f5e68c8205281d68bbb290"),
"user" : {
"firstName" : "testuser1",
"emailAddress" : "testuser1@test.com",
"password" : "test1@123",
"userAccessType" : "admin"
}
}
使用位置投影
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);