database - Array handling in mongodb
问题描述
I have the following two objects in my mongo db.
{
"schema":
{
"tag1": [
{
"path": "/homeAddress",
"sourceId": "1234"
}],
"something1": [
{
"path": "/Profile/properties/id",
}],
"iwantthis": [
{
"namespace": ["namespace1"]
},
{
"namespace": ["namespace2"]
}],
}
}
{
"schema":
{
"tag1": [
{
"path": "/homeAddress",
"sourceId": "1234"
}],
"something1": [
{
"path": "/Profile/properties/id",
}],
"iwantthis": [
{
"namespace": ["namespace3"]
},
{
"namespace": ["namespace4"]
}],
}
}
I am given two namespaces:
namespace1
namespace2
I have to form a query to fetch all the objects that have the two namespaces mentioned above.
MongoDB reference guide is not very helpful here. Any thoughts please?
解决方案
You can use $elemMatch
operator to find inside the array with $in
operator
db.collection.find({
"schema.iwantthis": {
"$elemMatch": {
"namespace": { "$in": ["namespace1", "namespace2"] }
}
}
})
推荐阅读
- laravel - 如何通过 bcrypt 函数将密码从种子插入数据库我的代码如下所示
- sql-server - 使用子选择向视图添加更多列
- java - 换行符换行符
- sql - T-SQL:WHERE <> 返回错误结果
- r - 如何为 data.table 中的左连接创建匹配标志
- android - Android Studio 找不到 com.jakewharton:butterknife-compiler:5.1.2
- javascript - Diamond-Square 实现产生过高的值
- reactjs - 如果日期是该月的最后一天,则在 d3 折线图中无法看到月份名称
- mysql - 协助 MySQL 'LIKE' 语句
- reactjs - 在循环内为变量赋值 - Express.js