我正在查询包含示例中显示的条目的数据库。所有条目都包含以下值:
_id
overallitem
:和的唯一标识placed_items
name
: 你的名字overallitem
loc
:overallitem
和的位置placed_items
time_id
:overallitem
存储时间placed_items
:包含数组placed_items
(范围可以从零:placed_items : [],
到无限量。category_id
: 的类别placed_items
full_id
: 的完整 idplaced_items
我想在给定和约束的每个级别上提取name
,full_id
和category_id
placed_items
time_id
loc
示例数据:
{
"_id" : "5040",
"name" : "entry1",
"loc" : 1,
"time_id" : 20121001,
"placed_items" : [],
}
{
"_id" : "5041",
"name" : "entry2",
"loc" : 1,
"time_id" : 20121001,
"placed_items" : [
{
"_id" : "5043",
"category_id" : 101,
"full_id" : 901,
},
{
"_id" : "5044",
"category_id" : 102,
"full_id" : 902,
}
],
}
{
"_id" : "5042",
"name" : "entry3",
"loc" : 1,
"time_id" : 20121001,
"placed_items" : [
{
"_id" : "5045",
"category_id" : 101,
"full_id" : 903,
},
],
}
此示例的预期结果是:
"name" "full_id" "category_id"
"entry2" 901 101
"entry2" 902 102
"entry3" 903 101
因此,如果placed_items
为空,请将条目放入数据框中,如果placed_items
包含n
条目,则将n
条目放入数据框中
我试图制定一个 RBlogger 示例来创建所需的数据框。
#Set up database
mongo <- mongo.create()
#Set up condition
buf <- mongo.bson.buffer.create()
mongo.bson.buffer.append(buf, "loc", 1)
mongo.bson.buffer.start.object(buf, "time_id")
mongo.bson.buffer.append(buf, "$gte", 20120930)
mongo.bson.buffer.append(buf, "$lte", 20121002)
mongo.bson.buffer.finish.object(buf)
query <- mongo.bson.from.buffer(buf)
#Count
count <- mongo.count(mongo, "items_test.overallitem", query)
#Note that these counts don't work, since the count should be based on
#the number of placed_items in the array, and not the number of entries.
#Setup Cursor
cursor <- mongo.find(mongo, "items_test.overallitem", query)
#Create vectors, which will be filled by the while loop
name <- vector("character", count)
full_id<- vector("character", count)
category_id<- vector("character", count)
i <- 1
#Fill vectors
while (mongo.cursor.next(cursor)) {
b <- mongo.cursor.value(cursor)
order_id[i] <- mongo.bson.value(b, "name")
product_id[i] <- mongo.bson.value(b, "placed_items.full_id")
category_id[i] <- mongo.bson.value(b, "placed_items.category_id")
i <- i + 1
}
#Convert to dataframe
results <- as.data.frame(list(name=name, full_id=full_uid, category_id=category_id))
如果我想在某个overallitem
级别(即_id
or name
)提取值但无法收集placed_items
级别上的信息,则条件有效并且代码有效。此外,提取的虚线调用full_id
似乎category_id
不起作用。任何人都可以帮忙吗?