[英]Find sample documents in mongo where a nested field matches a value
I have millions of records in collection and here are some sample documents我收集了数百万条记录,这里有一些示例文档
{
_id: ObjectId("003fjasf0234j03j0349")
FirstLayer: {
SecondLayer: {
Status: {
9428f:{
active: "Active"
}
}
}
}
}
{
_id: ObjectId("qg3o4034034nr34343")
FirstLayer: {
SecondLayer: {
Status: {
9428f:{
active: "Active"
}
}
}
}
}
{
_id: ObjectId("293je2odjojwe0f23")
FirstLayer: {
SecondLayer: {
Status: {
00fekw:{
active: "Not Active"
}
}
}
}
}
I want to fetch a few sample documents from monogdb where the active: "Active"
.我想从 monogdb 中获取一些示例文档,其中
active: "Active"
。 I came up with this:我想出了这个:
db.Collection.aggregate([
{$match:{"FirstLayer.SecondLayer.Status.9428f.active": "Active"}},
{$sample:{size: 50}}
])
It's working but the issue is the sub document inside Stauts {}
have different names for documents (ex: "9428f", "00fekw" in the given sample documents).它可以工作,但问题是
Stauts {}
中的子文档具有不同的文档名称(例如:给定示例文档中的“9428f”、“00fekw”)。 So I can't hard code the path to "active" field.所以我不能硬编码“活动”字段的路径。
Is there any other way to do it?还有其他方法吗?
I don't think is there any straight way to handle this situation in MongoDB,我认为在 MongoDB 中没有任何直接的方法可以处理这种情况,
You can try,你可以试试,
Approach 1:方法一:
$set
to add a field Status
to assign value of Status
after converting it to array in key-value format using $objectToArray
$set
添加一个字段Status
以在使用$objectToArray
将其转换为键值格式的数组后分配Status
的值$match
match Status condition $match
匹配状态条件$unset
remove Status
field because its not needed $unset
删除Status
字段,因为它不需要$sample
your documents $sample
你的文件db.collection.aggregate([
{ $set: { Status: { $objectToArray: "$FirstLayer.SecondLayer.Status" } } },
{ $match: { "Status.v.active": "Active" } },
{ $unset: "Status" },
{ $sample: { size: 50 } }
])
Approach 2:方法二:
Condition match with expression $expr
, you can use aggregation operators in condition,条件匹配表达式
$expr
,可以在条件中使用聚合运算符,
$let
to create a vars status
to get status array from object and in
filter status array and get active
status, $let
创建一个 vars status
以从 object 和过滤器状态数组in
获取状态数组并获取active
状态,$size
get size of above filter result $size
获取上述过滤结果的大小db.collection.aggregate([
{
$match: {
$expr: {
$let: {
vars: { status: { $objectToArray: "$FirstLayer.SecondLayer.Status" } },
in: {
$size: {
$filter: {
input: "$$status",
cond: { $eq: ["$$this.v.active", "Active"] }
}
}
}
}
}
}
},
{ $sample: { size: 50 } }
])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.